//
//  DataObject.m
//  iStock Global
//
//  Created by Andy on 2010/10/3.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//
#import "DBHelper.h"
#import "DataObject.h"
#import "DownloadData.h"
#import "StockTableQuote.h"
#import "ParaObject.h"
#import "LFcaluateTemp.h"
#import "HTMLNode.h"

@implementation DataObject
@synthesize financialData;
@synthesize financialData_Calcuate;
@synthesize financialData_TradeSystem;
@synthesize financialData_TradeSystem_Optimize;
@synthesize symbol;
@synthesize symbol_xxtradexx;
@synthesize name;
@synthesize id_class;
@synthesize overallLow;
@synthesize overallHigh;
@synthesize VoloverallLow;
@synthesize VoloverallHigh;
@synthesize delgete;
@synthesize dwm;
@synthesize aParaObject;
@synthesize volume_yahoo;
@synthesize EPS_Estimate_Current_Year_yahoo; //e7
@synthesize Price_EPS_Estimate_Next_Year_yahoo; //r6	
//@synthesize code;
@synthesize lastprice;
@synthesize s_open;
@synthesize s_high;
@synthesize s_low;



@synthesize tradedate;
@synthesize tradetime;
@synthesize updown;
@synthesize updownPercent;
@synthesize activity;
@synthesize his;
@synthesize Nupdwon;
@synthesize Nupdwonpercent;

@synthesize Finance_count;
@synthesize ChangePercent10day;
@synthesize ChangePercent5day;	
@synthesize ChangePercent20day;
@synthesize ChangePercent60day;
@synthesize ChangePercent120day;
@synthesize ChangePercent240day;
@synthesize ChangePercentWeek;
@synthesize ChangePercentMonth;	
@synthesize ChangePercentQuarter;
@synthesize ChangePercentYear;
//@synthesize LF_Signal;
//@synthesize LF_BreakP;
@synthesize LF_Signal1;
@synthesize LF_BreakP1;
@synthesize LF_Signal2;
@synthesize LF_BreakP2;
@synthesize LF_Signal3;
@synthesize LF_BreakP3;


@synthesize LF_Action1;
@synthesize LF_Action2;
@synthesize LF_Action3;

@synthesize cLF_b1;
@synthesize cLF_s1;
@synthesize cLF_bout1;
@synthesize cLF_sout1;	
@synthesize cLF_b2;
@synthesize cLF_s2;
@synthesize cLF_bout2;
@synthesize cLF_sout2;	
@synthesize cLF_b3;
@synthesize cLF_s3;
@synthesize cLF_bout3;
@synthesize cLF_sout3;

@synthesize LF_LongDay1;
@synthesize LF_LongDay2;	
@synthesize LF_LongDay3;
@synthesize LF_ShortgDay1;
@synthesize LF_ShortgDay2;
@synthesize LF_ShortgDay3;

@synthesize LF_LongProfit1;
@synthesize LF_LongProfit2;	
@synthesize LF_LongProfit3;
@synthesize LF_ShortgProfit1;
@synthesize LF_ShortgProfit2;
@synthesize LF_ShortgProfit3;	

@synthesize MESA_FAMA1;
@synthesize MESA_MAMA1;
@synthesize MESA_FAMA2;
@synthesize MESA_MAMA2;	
@synthesize MESA_FAMA3;
@synthesize MESA_MAMA3;

@synthesize MESA_bs1;
@synthesize MESA_bs2;
@synthesize MESA_bs3;	

@synthesize MESA_Signal1;
@synthesize MESA_Signal2;
@synthesize MESA_Signal3;	

@synthesize MESA_LongDay1;
@synthesize MESA_LongDay2;	
@synthesize MESA_LongDay3;
@synthesize MESA_ShortgDay1;
@synthesize MESA_ShortgDay2;
@synthesize MESA_ShortgDay3;

@synthesize MESA_LongProfit1;
@synthesize MESA_LongProfit2;	
@synthesize MESA_LongProfit3;
@synthesize MESA_ShortgProfit1;
@synthesize MESA_ShortgProfit2;
@synthesize MESA_ShortgProfit3;	


@synthesize havetocalcuateTableIndicator;
#pragma mark -
#pragma mark 初始化方法
-(id)init{
  
    self= [super init];
    
    if (self ) {
        
        
    }
	return self;
    
}
 
-(id)initWithTargetSymbol:(NSString *)aSymbol bname:(NSString *)cname  {
    self=[super init];
    
    if (self ) {
        
        symbol=aSymbol;
        name=cname;
        [self isUsexxTradexxForBackUpData]; //判斷是否採用xxtradexx 當作補充資料
    }
    return self;

    
}
-(void)Copy_symbol:(NSString *)obj{

    [symbol release];
     symbol=[obj copy] ;

} 
-(void)Copy_tradedate:(NSString *)obj{
    [tradedate release];
    tradedate=[obj copy] ;    
    
}
-(void)Copy_tradetime:(NSString *)obj{
    [tradetime release];
    tradetime=[obj copy] ;
}
-(void)Copy_updown:(NSString *)obj{
    [updown release];
    updown=[obj copy] ;
}
-(void)Copy_updownPercent:(NSString *)obj{
    [updownPercent release];
    updownPercent=[obj copy] ;
}
-(void)Copy_open:(NSString *)obj{

    [s_open release];
    s_open=[obj copy] ;
}
-(void)Copy_high:(NSString *)obj{
    [s_high release];
    s_high=[obj copy] ;    
    
}
-(void)Copy_low:(NSString *)obj{
    [s_low release];
    s_low=[obj copy] ; 
}


#pragma mark -
#pragma mark 資料寫入檔案方法

-(NSString *)pathForSymbol:(NSString *)aSymbol{
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
	NSString *documentsDirectory = [paths objectAtIndex:0];
	NSString *docPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist", aSymbol]];
	return docPath;
}
- (BOOL)writeToFile:(NSString *)path atomically:(BOOL)flag{
   // NSLog(@"writeToFile:%@", path);
    BOOL success = [[self plistRep] writeToFile:path atomically:flag];
    return success;
}
- (NSDictionary *)plistRep{
    NSMutableDictionary *rep = [NSMutableDictionary dictionaryWithCapacity:7];
    [rep setObject:[self symbol] forKey:@"symbol"];
	[rep setObject:[self financialData] forKey:@"financalData"];
	[rep setObject:[self overallHigh] forKey:@"overallHigh"];
    [rep setObject:[self overallLow] forKey:@"overallLow"];
	[rep setObject:[self VoloverallHigh] forKey:@"VoloverallHigh"];
    [rep setObject:[self VoloverallLow] forKey:@"VoloverallLow"];	
	
    return [NSDictionary dictionaryWithDictionary:rep];
}


-(NSString *)CpathForSymbol:(NSString *)aSymbol{
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
	NSString *documentsDirectory = [paths objectAtIndex:0];
	NSString *docPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@_C.plist", aSymbol]];
	return docPath;
}
- (BOOL)CwriteToFile:(NSString *)path atomically:(BOOL)flag{
	// NSLog(@"writeToFile:%@", path);
    BOOL success = [[self CplistRep] writeToFile:path atomically:flag];
    return success;
}
- (NSDictionary *)CplistRep{
    NSMutableDictionary *rep = [NSMutableDictionary dictionaryWithCapacity:2];
    [rep setObject:[self symbol] forKey:@"symbol"];
	[rep setObject:[self financialData_Calcuate] forKey:@"financialData_Calcuate"];
	//[rep setObject:[self overallHigh] forKey:@"overallHigh"];
    //[rep setObject:[self overallLow] forKey:@"overallLow"];
	//[rep setObject:[self VoloverallHigh] forKey:@"VoloverallHigh"];
    //[rep setObject:[self VoloverallLow] forKey:@"VoloverallLow"];	
	
    return [NSDictionary dictionaryWithDictionary:rep];
}

#pragma mark -
#pragma mark 取的檔案歷史資料
//取出檔案路徑
-(NSString *)faultTolerantPathForSymbol:(NSString *)aSymbol
{
    NSString *docPath = [self pathForSymbol:aSymbol];;
    if (![[NSFileManager defaultManager] fileExistsAtPath:docPath]) {
        //if there isn't one in the user's documents directory, see if we ship with this data
        docPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist", aSymbol]];
    }
    return docPath;
}
//取出資料檔案
-(NSDictionary *)dictionaryForSymbol:(NSString *)aSymbol
{
    NSString *path = [self faultTolerantPathForSymbol:aSymbol];
    NSMutableDictionary *localPlistDict = [NSMutableDictionary dictionaryWithContentsOfFile:path];
    return localPlistDict; 
}
//匯入記憶體
-(void)memoryWithDictionary:(NSDictionary *)aDict targetSymbol:(NSString *)aSymbol{
    
 
	//symbol =[[aDict objectForKey:@"symbol"] copy];
	 
	self.overallLow =   [NSDecimalNumber decimalNumberWithDecimal:[[aDict objectForKey:@"overallLow"] decimalValue]]   ;
	self.overallHigh =   [NSDecimalNumber decimalNumberWithDecimal:[[aDict objectForKey:@"overallHigh"] decimalValue]]    ;
	self.VoloverallLow =  [NSDecimalNumber decimalNumberWithDecimal: [[aDict objectForKey:@"VoloverallHigh"] decimalValue]]    ;
	self.VoloverallHigh =   [NSDecimalNumber decimalNumberWithDecimal:[[aDict objectForKey:@"VoloverallLow"] decimalValue]]  ;
	 
	 
	self.financialData =[aDict objectForKey:@"financalData"];
    
    

}

#pragma mark -
#pragma mark 取消下載
-(void)canceldownload{
	
	//downloadobject=nil;
    [downloadobject release];
     downloadobject=[[DownloadData alloc]init];		
}
#pragma mark -
#pragma mark 判断是否为浮点形：
- (BOOL)isPureFloat:(NSString*)string{
    NSScanner* scan = [NSScanner scannerWithString:string]; 
    float val; 
    return[scan scanFloat:&val] && [scan isAtEnd];
}



#pragma mark -
#pragma mark 1.取出資料的開頭程序 分兩種 有無歷史資料檔分界
//取出資料的開頭程序 是-(BOOL)getYahooHistroryDataSymbol

-(BOOL)getYahooHistroryDatagraphindex:(NSUInteger)aindex 					  
						  writetofile:(BOOL)WriteToFile 
							drawChart:(BOOL)bdrawchart 
		   closeCellActivityIndicator:(BOOL)bcloseCellActivityIndicator 
					 isuseNavagarator:(BOOL)isnavcontroller
				 isresetGraphLocation:(BOOL)aisresetGraphLocation 
						   isOptimize:(BOOL)isOptimizeTradeSystem
			  isCaluateTableIndicator:(BOOL)isCaluateTableIndicator{
	
	 
	//NSLog(@"ID_CLASS=%@",aid_class);
	
	
	//[self isUsexxTradexxForBackUpData]; //判斷是否採用xxtradexx 當作補充資料
	
	graph_index=aindex;
	getYahooHistroryData_writetofile=WriteToFile; //取玩資料之後是否要將檔案寫入檔案
	getYahooHistroryData_drawChart=bdrawchart; //取完資料之後是否要繪圖
	getYahooHistroryData_closeCellActivityIndicator=bcloseCellActivityIndicator;
	getYahooHistroryData_isuse_navcontroller=isnavcontroller;
	getYahooHistroryData_resetGraphLocation=aisresetGraphLocation;
	getYahooHistroryData_isOptimizeTradeSystem=isOptimizeTradeSystem;
    getYahooHistroryData_isCaluateTableIndicator=isCaluateTableIndicator;
	
	numberofweeks=100; //設定日資料往前推幾週
	
	//先檢查是否要進行最佳化程序
       
    
    
	if (getYahooHistroryData_isOptimizeTradeSystem==YES) {
		
        NSLog(@"要進行最佳化");	
		NSLog(@"getYahooHistroryDataSymbol_ 無資料檔案 start"); 	 
		
		
		NSMutableArray *temp;
		temp=[[NSMutableArray alloc] init];
		financialData=temp;
		
		//ㄧ次取出全部歷史資料
		[self getYahooAllHistroryData];
		
		NSLog(@"getYahooHistroryDataSymbol_ 無資料檔案  end");		 
		return NO;  //回答 no 表示目前的繪圖是透過網路截取			
		
		
		
	}
	else {
		NSLog(@"無進形最佳化");
		
		NSDictionary *cachedDictionary = [self dictionaryForSymbol:[symbol stringByAppendingString:dwm ]];
		
		if (nil != cachedDictionary) //檢查是否有歷史資料檔存在
		{
			NSLog(@"getYahooHistroryDataSymbol_有資料檔案 start1");  
			
			//檔案資料匯入記憶體中
			[self memoryWithDictionary:cachedDictionary targetSymbol:symbol ];
			
                        
            //計算最後日期
			NSDictionary *fData = (NSDictionary *)[financialData objectAtIndex:[financialData count]-1];		 
			NSDate *lastdate;
			lastdate=[fData objectForKey:@"date"];	
			
            NSDate *aStartDate = lastdate;
			NSDate *anEndDate = [NSDate date];				
			
             
            
			//開始下載部份歷史資料檔 標記為 rule1
			//標記:Yahoo與Google 資料選擇修改位置 歷史資料下載分野			
            NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
            if ([[prefs objectForKey:@"isYahoo"] boolValue]==YES){
                [self Download_Data:@"getYahooHistroryData_rule1" startDate:aStartDate endDate:anEndDate];	                
            }            
            else{
                [self Download_Data:@"getGoogleHistroryData_rule1" startDate:aStartDate endDate:anEndDate];	
            }
                        	
			
            
            
            
			NSLog(@"getYahooHistroryDataSymbol_有資料檔案  end");  
			
			//回答yes 表示資料已經內存在檔案中
			return YES;
		}	
		else {
			NSLog(@"getYahooHistroryDataSymbol_ 無資料檔案 start"); 	 
			
			
			NSMutableArray *temp;
			temp=[[NSMutableArray alloc] init];
			financialData=temp;
			 
			//ㄧ次取出全部歷史資料
			[self getYahooAllHistroryData];
			
			
			NSLog(@"getYahooHistroryDataSymbol_ 無資料檔案  end");		 
			return NO;  //回答 no 表示目前的繪圖是透過網路截取	 	 
		}
		
		
		
		
		
	}

	
	
	 
	
	
}

-(void)getYahooAllHistroryData{
	//先檢查是否要進行最佳化程序
	 NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];	
	
	if (getYahooHistroryData_isOptimizeTradeSystem==YES) {
		// 要進行最佳化 所以取出的起始日為 startOptimizeDate
		 
		//無預設值的情況
		if ([prefs objectForKey:@"startOptimizeDate"]==nil) {
			//設定全部時間
			NSTimeInterval secondsAgo = -timeIntervalForNumberOfWeeks(520); //預設10年期資料開始
			NSDate *aStartDate = [NSDate dateWithTimeIntervalSinceNow:secondsAgo]; 
			
			 
			[prefs setObject:aStartDate forKey:@"startOptimizeDate"];
			[prefs synchronize];			
			
		}				
		 
		
		
		//取出最佳化起始日期
						
		NSDate *aStartDate = [prefs objectForKey:@"startOptimizeDate"] 	; 
		NSDate *anEndDate = [NSDate date];			 
		
		//開始下載全部資料 標記為 rule2
			
		//標記:Yahoo與Google 資料選擇修改位置 歷史資料下載分野			
        NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
        if ([[prefs objectForKey:@"isYahoo"] boolValue]==YES){
            [self Download_Data:@"getYahooHistroryData_rule2" startDate:aStartDate endDate:anEndDate];	                
        }            
        else{
            [self Download_Data:@"getGoogleHistroryData_rule2" startDate:aStartDate endDate:anEndDate];	
        }
        
        
        
		
	}
	else {
		// 不是進行最佳化 所以取出的起始日為 startUseDate	
		
		//無預設值的情況
		if ([prefs objectForKey:@"startUseDate"]==nil) {
			//設定全部時間
			NSTimeInterval secondsAgo = -timeIntervalForNumberOfWeeks(104); //預設兩年期資料開始
			NSDate *aStartDate = [NSDate dateWithTimeIntervalSinceNow:secondsAgo]; 
			
			NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
			[prefs setObject:aStartDate forKey:@"startUseDate"];
			[prefs synchronize];			
			
		}		
		
		
		
		//取出設定的起始日期
		 				
        NSDate *aStartDate = [prefs objectForKey:@"startUseDate"]; 
		NSDate *anEndDate = [NSDate date];			 
		 
		//開始下載全部資料 標記為 rule2
		 	
		//標記:Yahoo與Google 資料選擇修改位置 歷史資料下載分野			
        NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
        if ([[prefs objectForKey:@"isYahoo"] boolValue]==YES){
            [self Download_Data:@"getYahooHistroryData_rule2" startDate:aStartDate endDate:anEndDate];	                
        }            
        else{
            [self Download_Data:@"getGoogleHistroryData_rule2" startDate:aStartDate endDate:anEndDate];	
        }
		
		
	}

	
		
	
}
#pragma mark -
#pragma mark 1.1判斷是否需要從xxtradexx 下載資料
-(void)isUsexxTradexxForBackUpData{
	NSArray *pdata=[self.symbol componentsSeparatedByString:@"."];	
	//pdata=[[NSArray alloc] init];
	
    //標記:增加一個市場，可以盤後回補當日資料 1 伺服器上的新增資料夾
	/*重要 如果要新增一個國家市場 要在xxtradexx 伺服器上增加兩個資料夾
     /database/realtime_data/新增國家碼
     /database/data/新增國家碼
    */
	
    //標記:增加一個市場，可以盤後回補當日資料 2 網路伺服器上的國家碼
    //標記:Add Target need Program xxTradexx網站伺服器資料夾新增    
    //此國家碼可以
    if ([pdata count]>=2) {	
		if ([[pdata objectAtIndex:1] isEqualToString:@"TWO"] || [[pdata objectAtIndex:1] isEqualToString:@"TW"]) {
			BoolIsUsexxTradexxForBackUpData=YES;
			self.symbol_xxtradexx= [ [pdata objectAtIndex:0]   stringByAppendingString:@".T"]   ;
		} 
		else if ([[pdata objectAtIndex:1] isEqualToString:@"HK"]){
			BoolIsUsexxTradexxForBackUpData=YES;
			self.symbol_xxtradexx= [ [pdata objectAtIndex:0]   stringByAppendingString:@".H"]   ;
			
			
		}
        else if ([[pdata objectAtIndex:1] isEqualToString:@"AX"]){
			BoolIsUsexxTradexxForBackUpData=YES;
			self.symbol_xxtradexx= [ [pdata objectAtIndex:0]   stringByAppendingString:@".AX"]   ;
			
			
		}        
        else if ([[pdata objectAtIndex:1] isEqualToString:@"SI"]){
			BoolIsUsexxTradexxForBackUpData=YES;
			self.symbol_xxtradexx= [ [pdata objectAtIndex:0]   stringByAppendingString:@".SI"]   ;
			
			
		}            
        
		else if ([[pdata objectAtIndex:1] isEqualToString:@"SS"] || [[pdata objectAtIndex:1] isEqualToString:@"SZ"]){
			BoolIsUsexxTradexxForBackUpData=YES;
			self.symbol_xxtradexx= [ [pdata objectAtIndex:0]   stringByAppendingString:@".C"]   ;
			
			
		}
		else if ([[pdata objectAtIndex:1] isEqualToString:@"FU"]){
			BoolIsUsexxTradexxForBackUpData=YES;
			self.symbol_xxtradexx= [ [pdata objectAtIndex:0]  stringByAppendingString:@".FU"]   ;
			
			
		}		
		
		
	}
	else {
		self.symbol_xxtradexx=[self.symbol stringByAppendingString:@".U"] ;
		BoolIsUsexxTradexxForBackUpData=NO;
	}
	
	
}



#pragma mark -
#pragma mark 2.啓動下載歷史資料 選項方法
-(void)Download_Data:(NSString *)identifier startDate:(NSDate*)astartDare endDate:(NSDate *)aendDate{
	
    NSString *urls;	
	NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];				
	if ([(NSString *)[prefs  objectForKey:@"isUseBackUPdatabase" ] isEqualToString:@"Y"]) {
		NSLog(@"如果是採用備援伺服器則是跳過從yahoo下載資料直接從xxtradexx下載資料"); 
		//如果是採用備援伺服器則是跳過從yahoo下載資料直接從xxtradexx下載資料
		NSDateFormatter* mmdd = [[NSDateFormatter alloc]init];
		[mmdd setDateFormat:@"yyyyMMdd"];
		NSString *wend = [mmdd stringFromDate:astartDare];		
		[mmdd release];
		urls = [NSString stringWithFormat:@"http://www.xxtradexx.com/database/read_dataiphone.aspx?code="];
		urls=[urls stringByAppendingString:symbol_xxtradexx]; //代碼 不含 .
		urls=[urls stringByAppendingString:@"&last_date="];
		urls=[urls stringByAppendingString:wend];
		urls=[urls stringByAppendingString:@"&last_adjust=-1"];
		urls = [urls stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];	
		identifier=@"getxxtradexxData_rule1" ;		
		NSLog(@"urls=%@",urls);
        
        
        //利用網路下載物件來下載資料
        if (downloadobject.loadingData==NO) {
            [downloadobject release];
            downloadobject=nil;
            downloadobject=[[DownloadData alloc]init];
            downloadobject.delgete=self;
            [downloadobject StartDownload:urls  
                               identifier:identifier];
            
            
        }	        
        
        
	}
	else {
        //標記:Yahoo與Google 資料選擇修改位置 歷史資料下載分野        
        if ([[prefs objectForKey:@"isYahoo"] boolValue]==YES)  {	
            //yahoo
            
            unsigned int unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit | NSYearCalendarUnit;
            
            NSCalendar *gregorian = [[NSCalendar alloc]
                                     initWithCalendarIdentifier:NSGregorianCalendar];		 
            NSDateComponents *compsStart = [gregorian components:unitFlags fromDate:astartDare];
            NSDateComponents *compsEnd = [gregorian components:unitFlags fromDate:aendDate];
            [gregorian release];
            //下載網址設定
            urls = [NSString stringWithFormat:@"http://ichart.yahoo.com/table.csv?s=%@&", self.symbol];
            urls = [urls stringByAppendingFormat:@"a=%d&",  [compsStart month]-1];
            urls = [urls stringByAppendingFormat:@"b=%d&",  [compsStart day]];
            
            
            if ([dwm isEqualToString: @"m"]) {
                urls = [urls stringByAppendingFormat:@"c=%d&",1980];
            }
            else if ([dwm isEqualToString: @"w"]){
                urls = [urls stringByAppendingFormat:@"c=%d&",2000];
            }
            else {
                urls = [urls stringByAppendingFormat:@"c=%d&", [compsStart year]];
            }
            
            
            
            urls = [urls stringByAppendingFormat:@"d=%d&",[compsEnd month]-1];
            urls = [urls stringByAppendingFormat:@"e=%d&",[compsEnd day]];
            urls = [urls stringByAppendingFormat:@"f=%d&",[compsEnd year]];
            
            
            urls = [urls stringByAppendingString:@"g="];
            urls = [urls stringByAppendingString:dwm];
            urls = [urls stringByAppendingString:@"&"];
            
            urls = [urls stringByAppendingString:@"ignore=.csv"];
            urls = [urls stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];	
            
            NSLog(@"yahoo urls=%@",urls);
        
            
            
            //利用網路下載物件來下載資料
            if (downloadobject.loadingData==NO) {
                
                [downloadobject release];
                
                downloadobject=nil;
                downloadobject=[[DownloadData alloc]init];
                downloadobject.delgete=self;
                
                [downloadobject StartDownload:urls  
                                   identifier:identifier];
                
                
            }	        
        }
        else{
        //google
            unsigned int unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit | NSYearCalendarUnit;
            
            NSCalendar *gregorian = [[NSCalendar alloc]
                                     initWithCalendarIdentifier:NSGregorianCalendar];		 
            NSDateComponents *compsStart = [gregorian components:unitFlags fromDate:astartDare];
            NSDateComponents *compsEnd = [gregorian components:unitFlags fromDate:aendDate];
            [gregorian release];
            
            NSString *start_string;
            NSString *end_string;
            
        
            
            
            if ([dwm isEqualToString:@"m"]) {
                start_string=[NSString stringWithFormat:@"%i-%i-%i",1990,1,1];
                end_string=[NSString stringWithFormat:@"%i-%i-%i",[compsEnd year],[compsEnd month],[compsEnd day]];                            
                
                           

            }
            else if ([dwm isEqualToString:@"w"]){
                start_string=[NSString stringWithFormat:@"%i-%i-%i",2000,1,1];
                end_string=[NSString stringWithFormat:@"%i-%i-%i",[compsEnd year],[compsEnd month],[compsEnd day]];                            

            }
            else {
                start_string=[NSString stringWithFormat:@"%i-%i-%i",[compsStart year],[compsStart month],[compsStart day]];
                end_string=[NSString stringWithFormat:@"%i-%i-%i",[compsEnd year],[compsEnd month],[compsEnd day]];                            
            }
            
            
           // NSLog(@"begin_download_google_history");
                      
            
            NSMutableArray *csvLines= [self Google_HistoryData_Daily:[self TickerConvert_yahoo_google:self.symbol] 
                                                        StartDates:start_string 
                                                          EndDates:end_string];
                       
                        
          
            
            
             NSMutableArray *datasplit;	
            datasplit=[[NSMutableArray alloc] init];
            
            //NSString *line=nil ;            
            self.overallHigh = [NSDecimalNumber notANumber];
			self.overallLow = [NSDecimalNumber notANumber];
			self.VoloverallHigh = [NSDecimalNumber notANumber];
			self.VoloverallLow = [NSDecimalNumber notANumber];				
			
			for (NSString *line in csvLines) {
				
				//line = (NSString *)[csvLines objectAtIndex:i];
				//NSLog(@"line=%@",line);
				
				NSArray *csvChunks ;
				//csvChunks=[[NSArray alloc]init];
				csvChunks=[line componentsSeparatedByString:@","];
				
				NSMutableDictionary *csvDict ;
				csvDict= [[NSMutableDictionary alloc] init];
				
				// Date,Open,High,Low,Close,Volume,Adj Close
				// 2009-06-08,143.82,144.23,139.43,143.85,33255400,143.85
				NSDate *theDate = [[NSDateFormatter yahooCSVDateFormatter] dateFromString:(NSString *)[csvChunks objectAtIndex:0]];
				[csvDict setObject:theDate forKey:@"date"];
				NSDecimalNumber *theOpen = [NSDecimalNumber decimalNumberWithString:(NSString *)[csvChunks objectAtIndex:1]];
				[csvDict setObject:theOpen forKey:@"open"];
				NSDecimalNumber *theHigh = [NSDecimalNumber decimalNumberWithString:(NSString *)[csvChunks objectAtIndex:2]];
				[csvDict setObject:theHigh forKey:@"high"];
				NSDecimalNumber *theLow = [NSDecimalNumber decimalNumberWithString:(NSString *)[csvChunks objectAtIndex:3]];
				[csvDict setObject:theLow forKey:@"low"];    
				NSDecimalNumber *theClose = [NSDecimalNumber decimalNumberWithString:(NSString *)[csvChunks objectAtIndex:4]];
				[csvDict setObject:theClose forKey:@"close"];
				NSDecimalNumber *theVolume = [NSDecimalNumber decimalNumberWithString:(NSString *)[csvChunks objectAtIndex:5]];
				[csvDict setObject:theVolume forKey:@"volume"];
				NSDecimalNumber *theAdjClose = [NSDecimalNumber decimalNumberWithString:(NSString *)[csvChunks objectAtIndex:6]];
				[csvDict setObject:theAdjClose forKey:@"adjClose"];
				
				//====
				NSDecimalNumber *high = [csvDict objectForKey:@"high"];
				NSDecimalNumber *low = [csvDict objectForKey:@"low"];
				NSDecimalNumber *vol = [csvDict objectForKey:@"volume"];
				
				if ( [self.overallHigh isEqual:[NSDecimalNumber notANumber]] ) {
					self.overallHigh =  high ;
				}
				
				if ( [self.overallLow isEqual:[NSDecimalNumber notANumber]] ) {
					self.overallLow = low;
				}
				if ( [self.VoloverallHigh isEqual:[NSDecimalNumber notANumber]] ) {
					self.VoloverallHigh = vol;
				}
				
				if ( [self.VoloverallLow isEqual:[NSDecimalNumber notANumber]] ) {
					self.VoloverallLow = vol;
				}					
				
				if ( [low compare:self.overallLow] == NSOrderedAscending )  {
					self.overallLow = low;
				}
				if ( [high compare:self.overallHigh] == NSOrderedDescending ) {
					self.overallHigh = high;
				}
				
				if ( [vol compare:self.VoloverallLow] == NSOrderedAscending )  {
					self.VoloverallLow = vol;
				}
				if ( [vol compare:self.VoloverallHigh] == NSOrderedDescending ) {
					self.VoloverallHigh = vol;
				}					
				
				
				
				//====
				[datasplit addObject: csvDict  ];
				// [csvChunks autorelease];
				[csvDict release];
				
				
				
			}
            //完成歷史資料取得 並且將資料順序反轉置入資料陣列中
			
			//陣列反轉
			NSMutableArray *reversedArray; 
			reversedArray= [[[datasplit reverseObjectEnumerator]  allObjects] mutableCopy];	
            //注意 	mutableCopy			[datasplit autorelease];
			[datasplit release];
			//分析下載資料完畢之後命令
			NSArray *pdata=[identifier componentsSeparatedByString:@"_"];
			
		 	//開始執行下載資料結束後的動作
			/*
			 rule1 表示從檔案取出資料 之後在下載部份資料
			 rule2 表示之前沒有資料或是因為調整價格不同所以必須 全部取出資料 
			 */
			if ([(NSString *)[pdata objectAtIndex:1] isEqualToString:@"rule1" ]) {
				NSLog(@"rule1_start");
				//將部份新的資料匯入的 finance data
				NSMutableArray *HaveReverseArray;
				HaveReverseArray= reversedArray  ;
				//[reversedArray release];
                //將新取出的資料匯入到 financedata
				NSLog(@"HaveReverseArray count=%i",[HaveReverseArray count]);
				if ( [HaveReverseArray count] > 0) {
					NSLog(@"判斷 最後一筆 與取出最新一筆的調整價格是否相同");
					//判斷 最後一筆 與取出最新一筆的調整價格是否相同
					
                    if ([financialData count]<1) {
                        NSLog(@"*******資料錯誤******");
                        [reversedArray release];
                        return;
                    }
                    NSDictionary *fData = (NSDictionary *)[financialData objectAtIndex:[financialData count]-1 ];
					
					NSDecimalNumber *fnum;// = [NSDecimalNumber zero];
					fnum = [fData objectForKey:@"adjClose"]; //調整價格	
					//NSDate *fdate;
					//fdate=[fData objectForKey:@"date"]; // 日期
					
					NSDateFormatter* df;
                    df= [[NSDateFormatter alloc]init];
					[df setDateFormat:@"yyyy/MM/dd"];
					[df release];
					
					//HaveReverseArray 是網路下載資料陣列
					NSDictionary *tData = (NSDictionary *)[HaveReverseArray objectAtIndex:0 ];
					NSDecimalNumber *tnum ;//= [NSDecimalNumber zero];
					tnum = [tData objectForKey:@"adjClose"];	
					//NSDate *tdate;
					//tdate=[tData objectForKey:@"date"];	
				  	
					if (![[fnum stringValue] isEqualToString:[tnum stringValue]]   ) {
						//表示調整後的價格不一樣 需要重新取出資料
						NSLog(@"表示調整後的價格不一樣 需要重新取出資料");
						
						[financialData removeAllObjects];
						NSLog(@"ㄧ次取出全部歷史資料");
						//ㄧ次取出全部歷史資料
						[self getYahooAllHistroryData];
						
					}
					else if([[fnum stringValue] isEqualToString:[tnum stringValue]]  ){
						NSLog(@"表示調整後的價格一樣 直接加入股票資料");		
						
						if ([HaveReverseArray count]>=2) {
							
							//新下載資料數目要超過2 
							for (int h=1; h<[HaveReverseArray count]; h++) {
								[financialData addObject:[HaveReverseArray objectAtIndex:h]];
								
							}	
							
							
						}
						NSLog(@"YahooData網路下載結束後啓動繪圖方法 是否儲存檔案");
						//YahooData網路下載結束後啓動繪圖方法 是否儲存檔案						
						[self afterDownloadYahooData];
					}
					else {
						NSLog(@"資料有斷層無法銜接");
					}
					
					
					
					
					
					
					
				}
                // [HaveReverseArray release];
                
			}
            
			else if([(NSString *)[pdata objectAtIndex:1] isEqualToString:@"rule2" ]){
				NSLog(@"rule2_start");				
			 	//重新下載全部歷史資料 不用下載部份資料
				//=======
				financialData= [reversedArray mutableCopy] ;
				
                
				
				//網路下載結束後啓動繪圖方法 是否儲存檔案
				[self afterDownloadYahooData];
				
				NSLog(@"rule2_end");					
			}
            [reversedArray release];  
            
             
            
            
            
        }
               
        
    }
    
        
     
		
		 

		 
}

#pragma mark -
#pragma mark 3.網路下載資料物件結束後的  delegate 方法


-(void)Download_Finish:(NSString *)datas Oidentifier:(NSString*)OutIdentifier{
	NSLog(@"Download_Finish_start_%@",OutIdentifier  );
	/*
	 下載資料 的來源
	 1.getYahooHistroryData :取的yahooo 歷史資料
	 2.getxxtradexxData :取的自設 從xxtradexx 下載的部份歷史資料
	 3.getYahooTodayData :取的 yahoo的 日資料	 目前此段程式無用主要是因為 已經將最後一筆報價資料改由tablequote上的資料來取代 
	 */
	NSAutoreleasePool *pool=[[NSAutoreleasePool alloc] init];	
	NSArray *csvLines ;	
	NSMutableArray *datasplit;	
	
	if ([OutIdentifier hasPrefix:@"getYahooHistroryData"]) {
		//下載的資料是 yahoo 歷史資料檔
		NSLog( @"Download_Finish_getYahooHistroryData_start"  );
		
		csvLines = [datas  componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
		//拆解資料
		
		datasplit=[[NSMutableArray alloc] init];
		NSString *line=nil ;
		line = (NSString *)[csvLines objectAtIndex:0];
		NSArray *csvChunks1 ;
		//csvChunks1=[[NSArray alloc]init];
		csvChunks1=[line componentsSeparatedByString:@","];			
		
		//判斷下載資料是否為有正確資料 用第一列的第一欄是否為日期資料
		if ([[csvChunks1 objectAtIndex:0] isEqual:@"Date"]) {
			
			self.overallHigh = [NSDecimalNumber notANumber];
			self.overallLow = [NSDecimalNumber notANumber];
			self.VoloverallHigh = [NSDecimalNumber notANumber];
			self.VoloverallLow = [NSDecimalNumber notANumber];				
			
			for (NSUInteger i=1; i<[csvLines count]-1; i++) {
				
				line = (NSString *)[csvLines objectAtIndex:i];
				//NSLog(@"%@",line);
				
				NSArray *csvChunks ;
				//csvChunks=[[NSArray alloc]init];
				csvChunks=[line componentsSeparatedByString:@","];
				
				NSMutableDictionary *csvDict ;
				csvDict= [[NSMutableDictionary alloc] init];
				
				// Date,Open,High,Low,Close,Volume,Adj Close
				// 2009-06-08,143.82,144.23,139.43,143.85,33255400,143.85
				NSDate *theDate = [[NSDateFormatter yahooCSVDateFormatter] dateFromString:(NSString *)[csvChunks objectAtIndex:0]];
				[csvDict setObject:theDate forKey:@"date"];
				NSDecimalNumber *theOpen = [NSDecimalNumber decimalNumberWithString:(NSString *)[csvChunks objectAtIndex:1]];
				[csvDict setObject:theOpen forKey:@"open"];
				NSDecimalNumber *theHigh = [NSDecimalNumber decimalNumberWithString:(NSString *)[csvChunks objectAtIndex:2]];
				[csvDict setObject:theHigh forKey:@"high"];
				NSDecimalNumber *theLow = [NSDecimalNumber decimalNumberWithString:(NSString *)[csvChunks objectAtIndex:3]];
				[csvDict setObject:theLow forKey:@"low"];    
				NSDecimalNumber *theClose = [NSDecimalNumber decimalNumberWithString:(NSString *)[csvChunks objectAtIndex:4]];
				[csvDict setObject:theClose forKey:@"close"];
				NSDecimalNumber *theVolume = [NSDecimalNumber decimalNumberWithString:(NSString *)[csvChunks objectAtIndex:5]];
				[csvDict setObject:theVolume forKey:@"volume"];
				NSDecimalNumber *theAdjClose = [NSDecimalNumber decimalNumberWithString:(NSString *)[csvChunks objectAtIndex:6]];
				[csvDict setObject:theAdjClose forKey:@"adjClose"];
				
				//====
				NSDecimalNumber *high = [csvDict objectForKey:@"high"];
				NSDecimalNumber *low = [csvDict objectForKey:@"low"];
				NSDecimalNumber *vol = [csvDict objectForKey:@"volume"];
				
				if ( [self.overallHigh isEqual:[NSDecimalNumber notANumber]] ) {
					self.overallHigh =  high ;
				}
				
				if ( [self.overallLow isEqual:[NSDecimalNumber notANumber]] ) {
					self.overallLow = low;
				}
				if ( [self.VoloverallHigh isEqual:[NSDecimalNumber notANumber]] ) {
					self.VoloverallHigh = vol;
				}
				
				if ( [self.VoloverallLow isEqual:[NSDecimalNumber notANumber]] ) {
					self.VoloverallLow = vol;
				}					
				
				if ( [low compare:self.overallLow] == NSOrderedAscending )  {
					self.overallLow = low;
				}
				if ( [high compare:self.overallHigh] == NSOrderedDescending ) {
					self.overallHigh = high;
				}
				
				if ( [vol compare:self.VoloverallLow] == NSOrderedAscending )  {
					self.VoloverallLow = vol;
				}
				if ( [vol compare:self.VoloverallHigh] == NSOrderedDescending ) {
					self.VoloverallHigh = vol;
				}					
				
				
				
				//====
				[datasplit addObject: csvDict  ];
				// [csvChunks autorelease];
				[csvDict release];
				
				
				
			}	
			
			//完成歷史資料取得 並且將資料順序反轉置入資料陣列中
			
			//陣列反轉
			NSMutableArray *reversedArray; 
			reversedArray= [[[datasplit reverseObjectEnumerator]  allObjects] mutableCopy];	
            //注意 	mutableCopy			[datasplit autorelease];
			[datasplit release];
			//分析下載資料完畢之後命令
			NSArray *pdata=[OutIdentifier componentsSeparatedByString:@"_"];
			
		 	//開始執行下載資料結束後的動作
			/*
			 rule1 表示從檔案取出資料 之後在下載部份資料
			 rule2 表示之前沒有資料或是因為調整價格不同所以必須 全部取出資料 
			 */
			if ([(NSString *)[pdata objectAtIndex:1] isEqualToString:@"rule1" ]) {
				NSLog(@"rule1_start");
				//將部份新的資料匯入的 finance data
				NSMutableArray *HaveReverseArray;
				HaveReverseArray= reversedArray  ;
				//[reversedArray release];
                //將新取出的資料匯入到 financedata
				
				if ([HaveReverseArray count]>0) {
					
					//判斷 最後一筆 與取出最新一筆的調整價格是否相同
					
                    if ([financialData count]<1) {
                        NSLog(@"*******資料錯誤******");
                        [reversedArray release];
                        return;
                    }
                    NSDictionary *fData = (NSDictionary *)[financialData objectAtIndex:[financialData count]-1 ];
					
					NSDecimalNumber *fnum;// = [NSDecimalNumber zero];
					fnum = [fData objectForKey:@"adjClose"]; //調整價格	
					//NSDate *fdate;
					//fdate=[fData objectForKey:@"date"]; // 日期
					
					NSDateFormatter* df;
                    df= [[NSDateFormatter alloc]init];
					[df setDateFormat:@"yyyy/MM/dd"];
					[df release];
					
					//HaveReverseArray 是網路下載資料陣列
					NSDictionary *tData = (NSDictionary *)[HaveReverseArray objectAtIndex:0 ];
					NSDecimalNumber *tnum ;//= [NSDecimalNumber zero];
					tnum = [tData objectForKey:@"adjClose"];	
					//NSDate *tdate;
					//tdate=[tData objectForKey:@"date"];	
				  	
					if (![[fnum stringValue] isEqualToString:[tnum stringValue]]   ) {
						//表示調整後的價格不一樣 需要重新取出資料
						NSLog(@"表示調整後的價格不一樣 需要重新取出資料");
						
						[financialData removeAllObjects];
						
						//ㄧ次取出全部歷史資料
						[self getYahooAllHistroryData];
						
					}
					else if([[fnum stringValue] isEqualToString:[tnum stringValue]]  ){
						NSLog(@"表示調整後的價格一樣 直接加入股票資料");		
						
						if ([HaveReverseArray count]>=2) {
							
							//新下載資料數目要超過2 
							for (int h=1; h<[HaveReverseArray count]; h++) {
								[financialData addObject:[HaveReverseArray objectAtIndex:h]];
								
							}	
							
							
						}
						
						//YahooData網路下載結束後啓動繪圖方法 是否儲存檔案						
						[self afterDownloadYahooData];
					}
					else {
						NSLog(@"資料有斷層無法銜接");
					}
					
					
					
					
					
					
					
				}
               // [HaveReverseArray release];
                
			}
           
			else if([(NSString *)[pdata objectAtIndex:1] isEqualToString:@"rule2" ]){
				NSLog(@"rule2_start");				
			 	//重新下載全部歷史資料 不用下載部份資料
				//=======
				financialData= [reversedArray mutableCopy] ;
				
				 
				
				//網路下載結束後啓動繪圖方法 是否儲存檔案
				[self afterDownloadYahooData];
				
				NSLog(@"rule2_end");					
			}
             [reversedArray release];
		}
	    else {
			
			//表示網路可以 但是下載的數據資料有誤
            [datasplit release];
			if ([OutIdentifier isEqualToString:@"getYahooHistroryData_rule1"]) {
				//直接跳到 下一步驟
				[self afterDownloadYahooData];
			}
			else {
				
			    [self.delgete getERRORdownload:self.symbol];
			}
            
		}
		
		if (getYahooHistroryData_closeCellActivityIndicator) {
			[self.delgete closeCellActivityIndicator:graph_index symbol:self.symbol];
		}
		NSLog( @"Download_Finish_getYahooHistroryData_end"  );		
	}
	else if([OutIdentifier hasPrefix:@"getxxtradexxData"]){
		NSLog(@"success download getxxtradexxData");
		
		//將xxtradexx 取的的歷史資料加入至 finance data中
		
		NSArray *copm=[datas componentsSeparatedByString:@"<br>enddata<br>"];
		//表示有從 xxtradexx 下載到部份資料
		if ([copm count]>1) {
			NSArray *line=[[copm objectAtIndex:0] componentsSeparatedByString:@"<br>"];
			if ([line count]>=2) {
				//表示有拆解出資料可以使用
				//依照日週月選項 將資料加入至 financialData
				if ([dwm isEqualToString:@"d"]) {
					
					for (int k=1; k<[line count]; k++) {
						
						NSArray *linearrary=[[line objectAtIndex:k] componentsSeparatedByString:@"_"];
						 
						if ([linearrary count]>=7) {
							// 0: 日期 1:開 2:高 3: 低 4:收 6:成交量 5:應垓是調整股價
							
							NSMutableDictionary *xcsvDict ;
							xcsvDict= [[NSMutableDictionary alloc] init];
							//[xcsvDict autorelease];							 
							NSDate *theDate = [[NSDateFormatter xxtradexxDateFormatter] dateFromString:(NSString *)[linearrary objectAtIndex:0]];
							[xcsvDict setObject:theDate forKey:@"date"];	
							NSDecimalNumber *theOpen = [NSDecimalNumber decimalNumberWithString:(NSString *)[linearrary objectAtIndex:1]];
							[xcsvDict setObject:theOpen forKey:@"open"];
							NSDecimalNumber *theHigh = [NSDecimalNumber decimalNumberWithString:(NSString *)[linearrary objectAtIndex:2]];
							[xcsvDict setObject:theHigh forKey:@"high"];
							NSDecimalNumber *theLow = [NSDecimalNumber decimalNumberWithString:(NSString *)[linearrary objectAtIndex:3]];
							[xcsvDict setObject:theLow forKey:@"low"];    
							NSDecimalNumber *theClose = [NSDecimalNumber decimalNumberWithString:(NSString *)[linearrary objectAtIndex:4]];
							[xcsvDict setObject:theClose forKey:@"close"];
							NSDecimalNumber *theVolume = [NSDecimalNumber decimalNumberWithString:(NSString *)[linearrary objectAtIndex:6]];
							[xcsvDict setObject:theVolume forKey:@"volume"];
							NSDecimalNumber *theAdjClose = [NSDecimalNumber decimalNumberWithString:(NSString *)[linearrary objectAtIndex:4]];
							[xcsvDict setObject:theAdjClose forKey:@"adjClose"];							 
							
							[(NSMutableArray *)financialData addObject: xcsvDict  ];
							
							[xcsvDict release];
						}
						
					}
				 
					
				}
				else if([dwm isEqualToString:@"w"]){
					NSDecimalNumber *wHigh;
					NSDecimalNumber *wOpen;
					NSDecimalNumber *wLow;	
					NSDecimalNumber *wclose;
					NSDecimalNumber *wvolume;
					NSDate *lastday;
					
					//先取出最接近一筆的資料
					NSMutableDictionary *lData;
					 
					if ([financialData count]>0) {
						lData= [ financialData objectAtIndex:[financialData count]-1 ] ;					
						lastday=[lData objectForKey:@"date"];
						wOpen= [lData objectForKey:@"open"];
						wHigh= [lData objectForKey:@"high"];
						wLow=  [lData objectForKey:@"low"];;
						//wclose=  [lData objectForKey:@"close"];	
						wvolume=  [lData objectForKey:@"volume"];							
						
					}
					else {
						NSArray *linearrary=[[line objectAtIndex:1] componentsSeparatedByString:@"_"];						
						lastday = [[NSDateFormatter xxtradexxDateFormatter] dateFromString:(NSString *)[linearrary objectAtIndex:0]];
						
						
						wOpen = [NSDecimalNumber decimalNumberWithString:(NSString *)[linearrary objectAtIndex:1]];
						wHigh = [NSDecimalNumber decimalNumberWithString:(NSString *)[linearrary objectAtIndex:2]];
						wLow = [NSDecimalNumber decimalNumberWithString:(NSString *)[linearrary objectAtIndex:3]];
						wclose = [NSDecimalNumber decimalNumberWithString:(NSString *)[linearrary objectAtIndex:4]];
						wvolume = [NSDecimalNumber decimalNumberWithString:(NSString *)[linearrary objectAtIndex:6]];
						
						
						//新增
						NSMutableDictionary *xcsvDict ;
						xcsvDict= [[NSMutableDictionary alloc] init];
						//[xcsvDict autorelease];							 
						[xcsvDict setObject:lastday forKey:@"date"];	
						[xcsvDict setObject:wOpen forKey:@"open"];
						[xcsvDict setObject:wHigh forKey:@"high"];
						[xcsvDict setObject:wLow forKey:@"low"];    
						[xcsvDict setObject:wclose forKey:@"close"];
						[xcsvDict setObject:wvolume forKey:@"volume"];
						[xcsvDict setObject:wclose forKey:@"adjClose"];
						[(NSMutableArray *)financialData addObject: xcsvDict  ];
                        [xcsvDict release];
						
					}
				
					 
					//NSLog(@"aaa high=%@ low=%@",wHigh,wLow); 
					 
					//從取出的資料比對出新Ｋ線的高低收價
					for (int k=1; k<[line count]; k++) {
						
						NSArray *linearrary=[[line objectAtIndex:k] componentsSeparatedByString:@"_"];
						
						if ([linearrary count]>=7) {
							// 0: 日期 1:開 2:高 3: 低 4:收 6:成交量 5:應垓是調整股價
							NSDate *theDate = [[NSDateFormatter xxtradexxDateFormatter] dateFromString:(NSString *)[linearrary objectAtIndex:0]];
 
							NSDecimalNumber *theOpen = [NSDecimalNumber decimalNumberWithString:(NSString *)[linearrary objectAtIndex:1]];
							NSDecimalNumber *theHigh = [NSDecimalNumber decimalNumberWithString:(NSString *)[linearrary objectAtIndex:2]];
							NSDecimalNumber *theLow = [NSDecimalNumber decimalNumberWithString:(NSString *)[linearrary objectAtIndex:3]];
							NSDecimalNumber *theClose = [NSDecimalNumber decimalNumberWithString:(NSString *)[linearrary objectAtIndex:4]];
							NSDecimalNumber *theVolume = [NSDecimalNumber decimalNumberWithString:(NSString *)[linearrary objectAtIndex:6]];
						 
							//wvolume=[wvolume decimalNumberByAdding:theVolume]; 不相加 適因為無法預知yahoo的週日是算哪裡
							if ( [wHigh isEqual:[NSDecimalNumber notANumber]] ) {
								wHigh =  theHigh ;
							}
							
							if ( [wLow isEqual:[NSDecimalNumber notANumber]] ) {
								wLow = theLow;
							}	
							if ( [theLow compare:wLow] == NSOrderedAscending )  {
								wLow = theLow;
							}
							if ( [theHigh compare:wHigh] == NSOrderedDescending ) {
								wHigh= theHigh;
							}	
							wclose=theClose;
							//wvolume=[wvolume decimalNumberByAdding: [NSDecimalNumber decimalNumberWithString:@"0.5"]]; 
							 
						    if ([self Date_weekday:theDate]> [self Date_weekday:lastday]) {
								 								
								//表是在一週內 所以用替換
								//如何替換 financialData 中的資料
								//NSLog(@"表是在一週內 所以用替換");
								//NSLog(@"open=%0.02f high=%0.02f low=%0.02f close=%0.02f volume=%0.0f",[wOpen floatValue],[wHigh floatValue],[wLow floatValue],[wclose floatValue],[wvolume floatValue]);
								
								
								NSMutableDictionary *fData ;
								fData= [[financialData objectAtIndex:[financialData count]-1 ] mutableCopy] ;
								[fData setObject:lastday forKey:@"date"];								
								[fData setObject:wOpen forKey:@"open"];
								[fData setObject:wHigh forKey:@"high"];
								[fData setObject:wLow forKey:@"low"]; 
								[fData setObject:wclose forKey:@"close"];	
								[fData setObject:wclose forKey:@"adjClose"];
								[fData setObject:wvolume forKey:@"volume"];								
								[(NSMutableArray *)financialData replaceObjectAtIndex:[financialData count]-1  withObject:fData];
								[fData release];
							}
							else {
								//表示跨週需要新增 並且取出最後一筆資料
							 NSLog(@"表示跨週需要新增 並且取出最後一筆資料");
								
							//	NSLog(@"open=%0.02f high=%0.02f low=%0.02f close=%0.02f volume=%0.0f",[theOpen floatValue],[theHigh floatValue],[theLow floatValue],[theClose floatValue],[theVolume floatValue]);
								//新增
								NSMutableDictionary *xcsvDict ;
								xcsvDict= [[NSMutableDictionary alloc] init];
								//[xcsvDict autorelease];							 
								[xcsvDict setObject:theDate forKey:@"date"];	
								[xcsvDict setObject:theOpen forKey:@"open"];
								[xcsvDict setObject:theHigh forKey:@"high"];
								[xcsvDict setObject:theLow forKey:@"low"];    
								[xcsvDict setObject:theClose forKey:@"close"];
								[xcsvDict setObject:theVolume forKey:@"volume"];
								[xcsvDict setObject:theClose forKey:@"adjClose"];
								[(NSMutableArray *)financialData addObject: xcsvDict  ];	
								[xcsvDict release];
								
								lastday=theDate;
								wOpen= theOpen;
								wHigh=theHigh;
								wLow= theLow;
								//wclose=  theClose;
								wvolume= theVolume;					
							 							
								
								
							}

						}
						
						
					}
					
					 				
					
					
				}
				else if([dwm isEqualToString: @"m"]){
					NSDecimalNumber *wHigh;
					NSDecimalNumber *wOpen;
					NSDecimalNumber *wLow;	
					NSDecimalNumber *wclose;
					NSDecimalNumber *wvolume;
					NSDate *lastday;
					
					//先取出最接近一筆的資料
					NSMutableDictionary *lData;
					if ([financialData count]>0) {
						lData= [ financialData objectAtIndex:[financialData count]-1 ] ;					
						lastday=[lData objectForKey:@"date"];
						wOpen= [lData objectForKey:@"open"];
						wHigh= [lData objectForKey:@"high"];
						wLow=  [lData objectForKey:@"low"];;
						//wclose=  [lData objectForKey:@"close"];	
						wvolume=  [lData objectForKey:@"volume"];						
						
					}
					else {
							
						NSArray *linearrary=[[line objectAtIndex:1] componentsSeparatedByString:@"_"];						
						lastday = [[NSDateFormatter xxtradexxDateFormatter] dateFromString:(NSString *)[linearrary objectAtIndex:0]];
						 	
						wOpen = [NSDecimalNumber decimalNumberWithString:(NSString *)[linearrary objectAtIndex:1]];
						wHigh = [NSDecimalNumber decimalNumberWithString:(NSString *)[linearrary objectAtIndex:2]];
						wLow = [NSDecimalNumber decimalNumberWithString:(NSString *)[linearrary objectAtIndex:3]];
						wclose = [NSDecimalNumber decimalNumberWithString:(NSString *)[linearrary objectAtIndex:4]];
						wvolume = [NSDecimalNumber decimalNumberWithString:(NSString *)[linearrary objectAtIndex:6]];
						
					    //新增
						NSMutableDictionary *xcsvDict ;
						xcsvDict= [[NSMutableDictionary alloc] init];
						[xcsvDict autorelease];							 
						[xcsvDict setObject:lastday forKey:@"date"];	
						[xcsvDict setObject:wOpen forKey:@"open"];
						[xcsvDict setObject:wHigh forKey:@"high"];
						[xcsvDict setObject:wLow forKey:@"low"];    
						[xcsvDict setObject:wclose forKey:@"close"];
						[xcsvDict setObject:wvolume forKey:@"volume"];
						[xcsvDict setObject:wclose forKey:@"adjClose"];
						[(NSMutableArray *)financialData addObject: xcsvDict ];						
						
					}

									
					
					
					
					//NSLog(@"aaa high=%@ low=%@",wHigh,wLow); 
					//NSLog(@"qqq=%i",[self weekday:lastday]);
					//從取出的資料比對出新Ｋ線的高低收價
					for (int k=1; k<[line count]; k++) {
						
						NSArray *linearrary=[[line objectAtIndex:k] componentsSeparatedByString:@"_"];
						
						if ([linearrary count]>=7) {
							// 0: 日期 1:開 2:高 3: 低 4:收 6:成交量 5:應垓是調整股價
							NSDate *theDate = [[NSDateFormatter xxtradexxDateFormatter] dateFromString:(NSString *)[linearrary objectAtIndex:0]];
							NSLog(@"wqqq=%i",[self Date_month:theDate]);	
							NSDecimalNumber *theOpen = [NSDecimalNumber decimalNumberWithString:(NSString *)[linearrary objectAtIndex:1]];
							NSDecimalNumber *theHigh = [NSDecimalNumber decimalNumberWithString:(NSString *)[linearrary objectAtIndex:2]];
							NSDecimalNumber *theLow = [NSDecimalNumber decimalNumberWithString:(NSString *)[linearrary objectAtIndex:3]];
							NSDecimalNumber *theClose = [NSDecimalNumber decimalNumberWithString:(NSString *)[linearrary objectAtIndex:4]];
							NSDecimalNumber *theVolume = [NSDecimalNumber decimalNumberWithString:(NSString *)[linearrary objectAtIndex:6]];
							//wvolume=[wvolume decimalNumberByAdding:theVolume]; 不相加 適因為無法預知yahoo的週日是算哪裡
							if ( [wHigh isEqual:[NSDecimalNumber notANumber]] ) {
								wHigh =  theHigh ;
							}
							
							if ( [wLow isEqual:[NSDecimalNumber notANumber]] ) {
								wLow = theLow;
							}	
							if ( [theLow compare:wLow] == NSOrderedAscending )  {
								wLow = theLow;
							}
							if ( [theHigh compare:wHigh] == NSOrderedDescending ) {
								wHigh= theHigh;
							}	
							wclose=theClose;
							//wvolume=[wvolume decimalNumberByAdding: [NSDecimalNumber decimalNumberWithString:@"0.5"]]; 
							
						    if ([self Date_month:theDate]  == [self Date_month:lastday]) {
								//表是在一月內 所以用替換
								//如何替換 financialData 中的資料
								NSLog(@"表是在一週內 所以用替換");
								NSLog(@"open=%0.02f high=%0.02f low=%0.02f close=%0.02f volume=%0.0f",[wOpen floatValue],[wHigh floatValue],[wLow floatValue],[wclose floatValue],[wvolume floatValue]);
								
								
								NSMutableDictionary *fData ;
								fData=  [financialData objectAtIndex:[financialData count]-1 ]   ;
								[fData setObject:lastday forKey:@"date"];								
								[fData setObject:wOpen forKey:@"open"];
								[fData setObject:wHigh forKey:@"high"];
								[fData setObject:wLow forKey:@"low"]; 
								[fData setObject:wclose forKey:@"close"];	
								[fData setObject:wclose forKey:@"adjClose"];
								[fData setObject:wvolume forKey:@"volume"];								
								[(NSMutableArray *)financialData replaceObjectAtIndex:[financialData count]-1  withObject:fData];
								
							}
							else {
								//表示跨週需要新增 並且取出最後一筆資料
								NSLog(@"表示跨週需要新增 並且取出最後一筆資料");
								
								NSLog(@"open=%0.02f high=%0.02f low=%0.02f close=%0.02f volume=%0.0f",[theOpen floatValue],[theHigh floatValue],[theLow floatValue],[theClose floatValue],[theVolume floatValue]);
								//新增
								NSMutableDictionary *xcsvDict ;
								xcsvDict= [[NSMutableDictionary alloc] init];
								//[xcsvDict autorelease];							 
								[xcsvDict setObject:theDate forKey:@"date"];	
								[xcsvDict setObject:theOpen forKey:@"open"];
								[xcsvDict setObject:theHigh forKey:@"high"];
								[xcsvDict setObject:theLow forKey:@"low"];    
								[xcsvDict setObject:theClose forKey:@"close"];
								[xcsvDict setObject:theVolume forKey:@"volume"];
								[xcsvDict setObject:theClose forKey:@"adjClose"];
								[(NSMutableArray *)financialData addObject: xcsvDict  ];	
								[xcsvDict release];
								
								lastday=theDate;
								wOpen= theOpen;
								wHigh=theHigh;
								wLow= theLow;
								//wclose=  theClose;
								wvolume= theVolume;					
								
								
								
							}
							
						}
						
						
					}
					
					
					
					
				}
				
			
			
			}
			
		}
		
		//進行最後合併 日資料與繪圖動作
		[self afterDownloadAllHistoryData];
		
	}
    else if([OutIdentifier hasPrefix:@"getYahooTodayData"]){
		
		NSLog( @"getYahooTodayData_start=%@",symbol);
		//分析下載資料 
		BOOL isYahooDailyDataOK; //下載的日資料是否正常
		isYahooDailyDataOK=YES;
		
		NSArray *csvLines = [datas  componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
		NSString *line = nil;
		
		line = (NSString *)[csvLines objectAtIndex:0];
		 	//判斷字串是否為空白字串
			if([line length]>0)
			{
				NSArray *pdata=[line componentsSeparatedByString:@","];
				if ([pdata count]>2) {
					// 1: 收盤價 6:開盤價 7:最高價  8:最低價 9: 成交量
					//將code 雙引號消除方法
					 
					if ( !( [[pdata objectAtIndex:7] isEqualToString :@"N/A" ] || [[pdata objectAtIndex:8] isEqualToString :@"N/A" ]  || [[pdata objectAtIndex:1] isEqualToString :@"N/A" ] ||  [[pdata objectAtIndex:9] isEqualToString :@"N/A" ]) ) {
						//判斷是否為空資料
						if ([dwm isEqualToString:@"d"]) {
							NSMutableDictionary *csvDict ;
							csvDict= [[NSMutableDictionary alloc] init];					
							
							NSDate *theDate =  [[NSDateFormatter yahooDailyDateFormatter] dateFromString:(NSString *)[[pdata objectAtIndex:2] stringByReplacingOccurrencesOfString:@"\"" withString:@""]];
							
                           // NSLog(@"testdates=%@",(NSString *)[[pdata objectAtIndex:2] stringByReplacingOccurrencesOfString:@"\"" withString:@""]  );
                           
                            [csvDict setObject:theDate forKey:@"date"];
							
							//假如無開盤價的情況之下 使用現價為開盤價
							if ([[pdata objectAtIndex:6] isEqualToString :@"N/A" ]) {
								NSDecimalNumber *theOpen = [NSDecimalNumber decimalNumberWithString:(NSString *)[pdata objectAtIndex:1]];
								[csvDict setObject:theOpen forKey:@"open"];
							}
							else {
								
								NSDecimalNumber *theOpen = [NSDecimalNumber decimalNumberWithString:(NSString *)[pdata objectAtIndex:6]];
								[csvDict setObject:theOpen forKey:@"open"];
							}
							NSDecimalNumber *theHigh = [NSDecimalNumber decimalNumberWithString:(NSString *)[pdata objectAtIndex:7]];
							[csvDict setObject:theHigh forKey:@"high"];
							NSDecimalNumber *theLow = [NSDecimalNumber decimalNumberWithString:(NSString *)[pdata objectAtIndex:8]];
							[csvDict setObject:theLow forKey:@"low"];    
							NSDecimalNumber *theClose = [NSDecimalNumber decimalNumberWithString:(NSString *)[pdata objectAtIndex:1]];
							[csvDict setObject:theClose forKey:@"close"];
							NSDecimalNumber *theVolume = [NSDecimalNumber decimalNumberWithString:(NSString *)[pdata objectAtIndex:9]];
							[csvDict setObject:theVolume forKey:@"volume"];
							NSDecimalNumber *theAdjClose = [NSDecimalNumber decimalNumberWithString:(NSString *)[pdata objectAtIndex:1]];
							[csvDict setObject:theAdjClose forKey:@"adjClose"];					
							 
                            
							if ([theClose floatValue]>9999999) {
                                //收盤價資料過大不合理重取讀取
								[csvDict release];
                                NSLog(@"收盤價資料過大不合理重取讀取");
								isYahooDailyDataOK=NO;								
								[self afterDownloadAllHistoryData];	
							}
							else {
																
								//前一筆的日資料取出
								NSMutableDictionary *fData ;
								if ([financialData count]<1) {
                                    NSLog(@"*********資料錯誤********");
                                    [csvDict release];
                                    return;
                                }
                                fData= [financialData objectAtIndex:[financialData count]-1 ]   ;
								NSDate *lastdate;
								lastdate=[fData objectForKey:@"date"];
								
								if ([lastdate isEqualToDate:theDate]) {
									//替換資料
									//最後一筆日期資料與及時資料相同 表示收盤後 已經 xxtradexx已經上傳當日資料
									NSLog(@"最後一筆日期資料與及時資料相同 表示收盤後 已經 xxtradexx已經上傳當日資料");
									[(NSMutableArray *)financialData replaceObjectAtIndex:[financialData count]-1  withObject:csvDict];
                                    [csvDict release];
								}
								else{
									//新增一筆資料
									//表示最後一筆資料日期與及時日期不同 所以用加入的方法
									NSLog(@"表示最後一筆資料日期與及時日期不同 可能是在盤中 所以用加入的方法");
									[(NSMutableArray *)financialData addObject: csvDict  ];
                                    [csvDict release];
								}
								
								
								
							}

														
							
							
						}
						else if([dwm isEqualToString: @"w"]){
							NSDecimalNumber *wHigh;
							NSDecimalNumber *wOpen;
							NSDecimalNumber *wLow;	
							NSDecimalNumber *wclose;
							NSDecimalNumber *wvolume;
							NSDate *lastday;
							
							//先取出最接近一筆的資料
							NSMutableDictionary *lData;
							lData= [ financialData objectAtIndex:[financialData count]-1 ] ;					
							lastday=[lData objectForKey:@"date"];
							wOpen= [lData objectForKey:@"open"];
							wHigh= [lData objectForKey:@"high"];
							wLow=  [lData objectForKey:@"low"];;
							//wclose=  [lData objectForKey:@"close"];	
							wvolume=  [lData objectForKey:@"volume"];					
							
							
							
						 	//2.下載最新一筆資料 
						    NSDate *theDate =  [[NSDateFormatter yahooDailyDateFormatter] dateFromString:(NSString *)[[pdata objectAtIndex:2] stringByReplacingOccurrencesOfString:@"\"" withString:@""]];
							//假如無開盤價的情況之下 使用現價為開盤價
							NSDecimalNumber *theOpen;							if ([[pdata objectAtIndex:6] isEqualToString :@"N/A" ]) {
								 theOpen = [NSDecimalNumber decimalNumberWithString:(NSString *)[pdata objectAtIndex:1]];
							 }
							else {
								 theOpen = [NSDecimalNumber decimalNumberWithString:(NSString *)[pdata objectAtIndex:6]];
							}
						 	NSDecimalNumber *theHigh = [NSDecimalNumber decimalNumberWithString:(NSString *)[pdata objectAtIndex:7]];
						    NSDecimalNumber *theLow = [NSDecimalNumber decimalNumberWithString:(NSString *)[pdata objectAtIndex:8]];
							NSDecimalNumber *theClose = [NSDecimalNumber decimalNumberWithString:(NSString *)[pdata objectAtIndex:1]];
							NSDecimalNumber *theVolume = [NSDecimalNumber decimalNumberWithString:(NSString *)[pdata objectAtIndex:9]];
						 	 			
							if ([theClose floatValue]>9999999) {
                                //收盤價資料過大不合理重取讀取
								NSLog(@"收盤價資料過大不合理重取讀取");								
								isYahooDailyDataOK=NO;								
								[self afterDownloadAllHistoryData];	
							}							
							else {
								//isYahooDailyDataOK=YES;								
								
								//3.最後一根Ｋ線資料與下載最新一筆資料比較
								if ([theLow compare:wLow] == NSOrderedAscending )  {
									wLow = theLow;
								}
								if ( [theHigh compare:wHigh] == NSOrderedDescending ) {
									wHigh= theHigh;
								}	
								wclose=theClose;							
								
								
								//4.替換 financialData 中的最新的及時資料
								if ([self Date_weekday:theDate]> [self Date_weekday:lastday]) {
									//表是在一週內 所以用替換
									//如何替換 financialData 中的資料
									NSLog(@"表是在一週內 所以用替換");
									NSLog(@"open=%0.02f high=%0.02f low=%0.02f close=%0.02f volume=%0.0f",[wOpen floatValue],[wHigh floatValue],[wLow floatValue],[wclose floatValue],[wvolume floatValue]);
									
									NSMutableDictionary *fData ;
									fData= [[financialData objectAtIndex:[financialData count]-1 ] mutableCopy] ;
									
									[fData setObject:wHigh forKey:@"high"];
									[fData setObject:wLow forKey:@"low"]; 
									[fData setObject:wclose forKey:@"close"];	
									[fData setObject:wclose forKey:@"adjClose"];					
									[(NSMutableArray *)financialData replaceObjectAtIndex:[financialData count]-1  withObject:fData];
									
									[fData release];
									
								}
								else {
									//表示跨週需要新增 
									NSLog(@"表示跨週需要新增");							
									//新增
									NSMutableDictionary *xcsvDict ;
									xcsvDict= [[NSMutableDictionary alloc] init];
									//[xcsvDict autorelease];							 
									[xcsvDict setObject:theDate forKey:@"date"];	
									[xcsvDict setObject:theOpen forKey:@"open"];
									[xcsvDict setObject:theHigh forKey:@"high"];
									[xcsvDict setObject:theLow forKey:@"low"];    
									[xcsvDict setObject:theClose forKey:@"close"];
									[xcsvDict setObject:theVolume forKey:@"volume"];
									[xcsvDict setObject:theClose forKey:@"adjClose"];
									[(NSMutableArray *)financialData addObject: xcsvDict ];	
									
									[xcsvDict release];
									
									
									
									
								}								
								
								
							}

							
						}
						else if([dwm isEqualToString: @"m"]){
							NSDecimalNumber *wHigh;
							NSDecimalNumber *wOpen;
							NSDecimalNumber *wLow;	
							NSDecimalNumber *wclose;
							NSDecimalNumber *wvolume;
							NSDate *lastday;
							
							//先取出最接近一筆的資料
							NSMutableDictionary *lData;
							lData= [ financialData objectAtIndex:[financialData count]-1 ] ;
							lastday=[lData objectForKey:@"date"];
							wOpen= [lData objectForKey:@"open"];
							wHigh= [lData objectForKey:@"high"];
							wLow=  [lData objectForKey:@"low"];;
							//wclose=  [lData objectForKey:@"close"];	
							wvolume=  [lData objectForKey:@"volume"];					
							
							
							
						 	//2.下載最新一筆資料 
						    NSDate *theDate =  [[NSDateFormatter yahooDailyDateFormatter] dateFromString:(NSString *)[[pdata objectAtIndex:2] stringByReplacingOccurrencesOfString:@"\"" withString:@""]];
							//假如無開盤價的情況之下 使用現價為開盤價
							NSDecimalNumber *theOpen;							if ([[pdata objectAtIndex:6] isEqualToString :@"N/A" ]) {
								theOpen = [NSDecimalNumber decimalNumberWithString:(NSString *)[pdata objectAtIndex:1]];
							}
							else {
								theOpen = [NSDecimalNumber decimalNumberWithString:(NSString *)[pdata objectAtIndex:6]];
							}
						 	NSDecimalNumber *theHigh = [NSDecimalNumber decimalNumberWithString:(NSString *)[pdata objectAtIndex:7]];
						    NSDecimalNumber *theLow = [NSDecimalNumber decimalNumberWithString:(NSString *)[pdata objectAtIndex:8]];
							NSDecimalNumber *theClose = [NSDecimalNumber decimalNumberWithString:(NSString *)[pdata objectAtIndex:1]];
							NSDecimalNumber *theVolume = [NSDecimalNumber decimalNumberWithString:(NSString *)[pdata objectAtIndex:9]];
							
							
							if ([theClose floatValue]>9999999) {
                                //收盤價資料過大不合理重取讀取
								NSLog(@"收盤價資料過大不合理重取讀取");								
								isYahooDailyDataOK=NO;								
								[self afterDownloadAllHistoryData];	
							}							
							else {
								//isYahooDailyDataOK=YES;								
								//3.最後一根Ｋ線資料與下載最新一筆資料比較
								if ([theLow compare:wLow] == NSOrderedAscending )  {
									wLow = theLow;
								}
								if ( [theHigh compare:wHigh] == NSOrderedDescending ) {
									wHigh= theHigh;
								}	
								wclose=theClose;							
								
								
								//4.替換 financialData 中的最新的及時資料
								if ([self Date_month:theDate] == [self Date_month:lastday]) {
									//表是在一週內 所以用替換
									//如何替換 financialData 中的資料
									NSLog(@"表是在一週內 所以用替換");
									NSLog(@"open=%0.02f high=%0.02f low=%0.02f close=%0.02f volume=%0.0f",[wOpen floatValue],[wHigh floatValue],[wLow floatValue],[wclose floatValue],[wvolume floatValue]);
									
									NSMutableDictionary *fData ;
									fData=  [[financialData objectAtIndex:[financialData count]-1 ] mutableCopy]   ;
									
									[fData setObject:wHigh forKey:@"high"];
									[fData setObject:wLow forKey:@"low"]; 
									[fData setObject:wclose forKey:@"close"];	
									[fData setObject:wclose forKey:@"adjClose"];					
									[(NSMutableArray *)financialData replaceObjectAtIndex:[financialData count]-1  withObject:fData];
									
									[fData release];
									
								}
								else {
									//表示跨週需要新增 
									NSLog(@"表示跨週需要新增");							
									//新增
									NSMutableDictionary *xcsvDict ;
									xcsvDict= [[NSMutableDictionary alloc] init];
									//[xcsvDict autorelease];							 
									[xcsvDict setObject:theDate forKey:@"date"];	
									[xcsvDict setObject:theOpen forKey:@"open"];
									[xcsvDict setObject:theHigh forKey:@"high"];
									[xcsvDict setObject:theLow forKey:@"low"];    
									[xcsvDict setObject:theClose forKey:@"close"];
									[xcsvDict setObject:theVolume forKey:@"volume"];
									[xcsvDict setObject:theClose forKey:@"adjClose"];
									[(NSMutableArray *)financialData addObject: xcsvDict  ];	
									
									[xcsvDict release];
									
									
									
									
								}								
								
								
								
							}

						
							
							
							
						}
						
					}
				}						
				//重新刷新表格
			}
			
		if (isYahooDailyDataOK==YES) {
			[self afterDownloadYahooDailyData];
		}
		 //標記:繪圖結束後的最後位置 4.DataObject.m-getYahooTodayData
		NSLog( @"getYahooTodayData_end");
	}
	
	//datas=@"";
	//[csvLines release];
	 
	[pool release];
    //標記:繪圖結束後的最後位置 5.DataObject.m-Download_Finish: 
    
   NSLog(@"Download_Finish_end_%@",OutIdentifier  );
	
}
-(void)Download_didFailWithError:(NSError *)error Oidentifier:(NSString*)OutIdentifier{
	//網路下載資料失敗
	if (getYahooHistroryData_closeCellActivityIndicator) {
		[self.delgete closeCellActivityIndicator:graph_index symbol:self.symbol];
		[self.delgete DelgetestopAnimating];		
	}
	
	if ([OutIdentifier isEqualToString:@"getxxtradexxData_rule1"]) {
		[self afterDownloadAllHistoryData];			
	}
	else {
		[self.delgete ObjectDownload_didFailWithError:error asymbol:self.symbol];
		
	}
	
	//[self.delgete ObjectDownload_didFailWithError:error asymbol:OutIdentifier];
	
}

 

#pragma mark -
#pragma mark 4.YahooData資料下載結束 

-(void)afterDownloadYahooData{
	NSLog(@"afterDownloadYahooData_start");
	
	 
	//是否要將資料存檔  資料存檔以yahoo 歷史資料為主 其他資料不存
	if (getYahooHistroryData_writetofile) {
		[self writeToFile:[self pathForSymbol:[self.symbol stringByAppendingString:dwm ]] atomically:YES];				
	}	
	 	
	//檢查判斷是否要二次下載資料 從 xxTradexx
	 
	if ( BoolIsUsexxTradexxForBackUpData==YES) {
		 
			NSLog(@"xxTradexx下載後續補充資料_start"); //下載標記 @"getxxtradexxData_rule1			  		
		   
			//製作要下載的資料ＵＲＬＳ
        if ([financialData count]<1) {
            NSLog(@"****資料錯誤******");
            return;
        }
        
			NSDictionary *fData = (NSDictionary *)[financialData objectAtIndex:[financialData count]-1 ];
			NSDate *fdate;
			fdate=[fData objectForKey:@"date"]; // 日期			
			NSDateFormatter* df = [[NSDateFormatter alloc]init];
			[df setDateFormat:@"yyyyMMdd"];
			NSString *result = [df stringFromDate:fdate];	//financedata 的最後一筆資料日期		
			
            [df release];
			NSString *urls = [NSString stringWithFormat:@"http://www.xxtradexx.com/database/read_dataiphone.aspx?code="];
			urls=[urls stringByAppendingString:symbol_xxtradexx]; //代碼 不含 .
			urls=[urls stringByAppendingString:@"&last_date="];
			urls=[urls stringByAppendingString:result];
			urls=[urls stringByAppendingString:@"&last_adjust=-1"];
			urls = [urls stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];	
			
		  
			//  NSLog(urls);
			//利用網路下載物件來下載資料
			if (downloadobject.loadingData==NO) {
				downloadobject=nil;
				downloadobject=[[DownloadData alloc]init];
				downloadobject.delgete=self;
				[downloadobject StartDownload:urls  
								   identifier:@"getxxtradexxData_rule1" ];
				
				
			}	
			NSLog(@"xxTradexx下載後續補充資料_end")	;		
	 
		
	}
	else {
	    //不經過xxtradexx 補充資料 列如美國市場
		//是否要將啓動繪圖
		NSLog(@"不經過xxtradexx 補充資料 列如美國市場");
		[self afterDownloadAllHistoryData];		
		
		
	}
	
	
	
	
	
	
	NSLog(@"afterDownloadYahooData_end");
}

             

#pragma mark -
#pragma mark 5.所有歷史資料下載結束 
-(void)afterDownloadAllHistoryData{
	 /*
	 //是否要將資料存檔  資料存檔以yahoo 歷史資料為主 其他資料不存
	 if (getYahooHistroryData_writetofile) {
	 [self writeToFile:[self pathForSymbol:[self.symbol stringByAppendingString:dwm ]] atomically:YES];				
	 }	
	 */
	//取出及時日資料
	
    
    /*
     後面這段程式是採用yahoo的日資料再次取出
	NSString *urls = [NSString stringWithFormat:@"http://download.finance.yahoo.com/d/quotes.csv?s="];
	urls=[urls stringByAppendingString:self.symbol];
	urls=[urls stringByAppendingString:@"&f=sl1d1t1c1p2ohgv&e=.csv"];
	 
	urls = [urls stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];	
	//利用網路下載物件來下載資料
	 
    if (downloadobject.loadingData==NO) {
		[downloadobject release];
		downloadobject=nil;
		downloadobject=[[DownloadData alloc]init];
		downloadobject.delgete=self;
		[downloadobject StartDownload:urls  
						   identifier:@"getYahooTodayData" ];
		
		
	}		
	*/
    
    
    //報價表上的今日股票資料
   // NSLog(@"/報價表上的今日股票資料");
  //  NSLog(@"tradedate=%@",tradedate);
   // NSLog(@"lastprice=%@",lastprice);
   // NSLog(@"open=%@",s_open); 
   // NSLog(@"high=%@",s_high);
  //  NSLog(@"low=%@",s_low);
   // NSLog(@"volume=%@",volume_yahoo);
      
    if ([dwm isEqualToString: @"d"]) {						
        NSMutableDictionary *csvDict ;
        csvDict= [[NSMutableDictionary alloc] init];					
        
        NSDate *theDate =  [[NSDateFormatter yahooDailyDateFormatter] dateFromString:tradedate];
        [csvDict setObject:theDate forKey:@"date"];
        
        BOOL useTabelQuoteAddInstry;
        useTabelQuoteAddInstry=YES;
        
         // 假如無開盤價的情況之下 使用現價為開盤價
        
        if ([self isPureFloat: s_open ]==NO) {
           useTabelQuoteAddInstry=NO;
        }
        if ([self isPureFloat: s_high ]==NO) {
            useTabelQuoteAddInstry=NO;
        }        
        if ([self isPureFloat: s_low ]==NO) {
            useTabelQuoteAddInstry=NO;
        }     
        
        
        
        NSDecimalNumber *theOpen = [NSDecimalNumber decimalNumberWithString:s_open];
        [csvDict setObject:theOpen forKey:@"open"];
        
        NSDecimalNumber *theHigh = [NSDecimalNumber decimalNumberWithString:s_high];
        [csvDict setObject:theHigh forKey:@"high"];
  
        NSDecimalNumber *theLow = [NSDecimalNumber decimalNumberWithString:s_low];
        [csvDict setObject:theLow forKey:@"low"];   
  
        NSDecimalNumber *theClose = [NSDecimalNumber decimalNumberWithString:lastprice];
        [csvDict setObject:theClose forKey:@"close"];
  
        NSDecimalNumber *theVolume ;
        if ([volume_yahoo hasSuffix:@"M"]) {
            //有百萬字串
                theVolume= [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%f",[ [volume_yahoo stringByReplacingOccurrencesOfString:@"M" withString:@"" ] floatValue]*1000000 ]  ]; 
        }
        else if ([volume_yahoo hasSuffix:@"B"]) {
            //有十億字串
            theVolume= [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%f",[ [volume_yahoo stringByReplacingOccurrencesOfString:@"B" withString:@"" ] floatValue]*1000000000 ]  ]; 
        }
        else{
               theVolume= [NSDecimalNumber decimalNumberWithString:[volume_yahoo stringByReplacingOccurrencesOfString:@"," withString:@""]];
        }
       
        
        [csvDict setObject:theVolume forKey:@"volume"];
  
        NSDecimalNumber *theAdjClose = [NSDecimalNumber decimalNumberWithString:lastprice];
       [csvDict setObject:theAdjClose forKey:@"adjClose"];					
        
        //前一筆的日資料取出
        NSMutableDictionary *fData ;
        if ([financialData count]<1) {
            NSLog(@"*********資料錯誤********");
            [csvDict release];
            return;
        }
        fData= [financialData objectAtIndex:[financialData count]-1 ]   ;
        NSDate *lastdate;
        lastdate=[fData objectForKey:@"date"];
        
        //NSLog(@"lastdate-thedate=%f",[lastdate timeIntervalSinceDate:theDate ]);
        
        if (useTabelQuoteAddInstry==YES) {
           
            if ([lastdate isEqualToDate:theDate]) {
                //替換資料
                //最後一筆日期資料與及時資料相同 表示收盤後 已經 xxtradexx已經上傳當日資料
                //NSLog(@"最後一筆日期資料與及時資料相同 表示收盤後 已經 xxtradexx已經上傳當日資料");
                [(NSMutableArray *)financialData replaceObjectAtIndex:[financialData count]-1  withObject:csvDict];
                 
            }
            else if([theDate timeIntervalSinceDate:lastdate ]>60*60*12 ) {
                //表示 報價表上的資料時間要大於最後一筆時間超過半天才 新增一筆資料
                //表示最後一筆資料日期與及時日期不同 所以用加入的方法
                
                NSLog(@"表示最後一筆資料日期與及時日期不同 可能是在盤中 所以用加入的方法");
                [(NSMutableArray *)financialData addObject: csvDict  ];
                
            }
            
             
        }
        
             
        [csvDict release];        
       
        
     
            
        [self afterDownloadYahooDailyData];          
        
        
        
        
    }
     
    else if([dwm isEqualToString: @"w"]){
        NSDecimalNumber *wHigh;
        NSDecimalNumber *wOpen;
        NSDecimalNumber *wLow;	
        NSDecimalNumber *wclose;
        NSDecimalNumber *wvolume;
        NSDate *lastday;
        
        //先取出最接近一筆的資料
        NSMutableDictionary *lData;
        lData= [ financialData objectAtIndex:[financialData count]-1 ] ;					
        lastday=[lData objectForKey:@"date"];
        wOpen= [lData objectForKey:@"open"];
        wHigh= [lData objectForKey:@"high"];
        wLow=  [lData objectForKey:@"low"];;
        //wclose=  [lData objectForKey:@"close"];	
        wvolume=  [lData objectForKey:@"volume"];					
        
        
        
        //2.下載最新一筆資料 
        NSDate *theDate =  [[NSDateFormatter yahooDailyDateFormatter] dateFromString:tradedate];
       
        BOOL useTabelQuoteAddInstry;
        useTabelQuoteAddInstry=YES;
        // 假如無開盤價的情況之下 使用現價為開盤價
        if ([self isPureFloat: s_open ]==NO) {
            useTabelQuoteAddInstry=NO;
        }
        if ([self isPureFloat: s_high ]==NO) {
            useTabelQuoteAddInstry=NO;
        }        
        if ([self isPureFloat: s_low ]==NO) {
            useTabelQuoteAddInstry=NO;
        }     
        
        
        
        
        //假如無開盤價的情況之下 使用現價為開盤價
        NSDecimalNumber *theOpen;							
       
        theOpen = [NSDecimalNumber decimalNumberWithString:s_open];
        
        NSDecimalNumber *theHigh = [NSDecimalNumber decimalNumberWithString:s_high];
        NSDecimalNumber *theLow = [NSDecimalNumber decimalNumberWithString:s_low];
        NSDecimalNumber *theClose = [NSDecimalNumber decimalNumberWithString:lastprice];
        NSDecimalNumber *theVolume ;
        if ([volume_yahoo hasSuffix:@"M"]) {
            //有百萬字串
            theVolume= [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%f",[ [volume_yahoo stringByReplacingOccurrencesOfString:@"M" withString:@"" ] floatValue]*1000000 ]  ]; 
        }
        else if ([volume_yahoo hasSuffix:@"B"]) {
            //有十億字串
            theVolume= [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%f",[ [volume_yahoo stringByReplacingOccurrencesOfString:@"B" withString:@"" ] floatValue]*1000000000 ]  ]; 
        }
        else{
            theVolume= [NSDecimalNumber decimalNumberWithString:[volume_yahoo stringByReplacingOccurrencesOfString:@"," withString:@""]];
        }
        
        //isYahooDailyDataOK=YES;								
        
        //3.最後一根Ｋ線資料與下載最新一筆資料比較
        if ([theLow compare:wLow] == NSOrderedAscending )  {
            wLow = theLow;
        }
        if ( [theHigh compare:wHigh] == NSOrderedDescending ) {
            wHigh= theHigh;
        }	
        wclose=theClose;							
        
        if (useTabelQuoteAddInstry==YES) {
            //4.替換 financialData 中的最新的及時資料
            if ([self Date_weekday:theDate]> [self Date_weekday:lastday]) {
                //表是在一週內 所以用替換
                //如何替換 financialData 中的資料
                NSLog(@"表是在一週內 所以用替換");
                NSLog(@"open=%0.02f high=%0.02f low=%0.02f close=%0.02f volume=%0.0f",[wOpen floatValue],[wHigh floatValue],[wLow floatValue],[wclose floatValue],[wvolume floatValue]);
                
                NSMutableDictionary *fData ;
                fData= [[financialData objectAtIndex:[financialData count]-1 ] mutableCopy] ;
                
                [fData setObject:wHigh forKey:@"high"];
                [fData setObject:wLow forKey:@"low"]; 
                [fData setObject:wclose forKey:@"close"];	
                [fData setObject:wclose forKey:@"adjClose"];					
                [(NSMutableArray *)financialData replaceObjectAtIndex:[financialData count]-1  withObject:fData];
                
                [fData release];
                
            }
            else {
                //表示跨週需要新增 
                NSLog(@"表示跨週需要新增");							
                //新增
                NSMutableDictionary *xcsvDict ;
                xcsvDict= [[NSMutableDictionary alloc] init];
                //[xcsvDict autorelease];							 
                [xcsvDict setObject:theDate forKey:@"date"];	
                [xcsvDict setObject:theOpen forKey:@"open"];
                [xcsvDict setObject:theHigh forKey:@"high"];
                [xcsvDict setObject:theLow forKey:@"low"];    
                [xcsvDict setObject:theClose forKey:@"close"];
                [xcsvDict setObject:theVolume forKey:@"volume"];
                [xcsvDict setObject:theClose forKey:@"adjClose"];
                [(NSMutableArray *)financialData addObject: xcsvDict ];	
                
                [xcsvDict release];
                
                
                
                
            }		    
        }
        
       						
            
            
         [self afterDownloadYahooDailyData];         
        
    }
   
    
    else if([dwm isEqualToString: @"m"]){
        NSDecimalNumber *wHigh;
        NSDecimalNumber *wOpen;
        NSDecimalNumber *wLow;	
        NSDecimalNumber *wclose;
        NSDecimalNumber *wvolume;
        NSDate *lastday;
        
        //先取出最接近一筆的資料
        NSMutableDictionary *lData;
        lData= [ financialData objectAtIndex:[financialData count]-1 ] ;					
        lastday=[lData objectForKey:@"date"];
        wOpen= [lData objectForKey:@"open"];
        wHigh= [lData objectForKey:@"high"];
        wLow=  [lData objectForKey:@"low"];;
        //wclose=  [lData objectForKey:@"close"];	
        wvolume=  [lData objectForKey:@"volume"];					
        
        
        
        //2.下載最新一筆資料 
        NSDate *theDate =  [[NSDateFormatter yahooDailyDateFormatter] dateFromString:tradedate];
        
        BOOL useTabelQuoteAddInstry;
        useTabelQuoteAddInstry=YES;
        // 假如無開盤價的情況之下 使用現價為開盤價
        if ([self isPureFloat: s_open ]==NO) {
            useTabelQuoteAddInstry=NO;
        }
        if ([self isPureFloat: s_high ]==NO) {
            useTabelQuoteAddInstry=NO;
        }        
        if ([self isPureFloat: s_low ]==NO) {
            useTabelQuoteAddInstry=NO;
        }             
        
        
        //假如無開盤價的情況之下 使用現價為開盤價
        NSDecimalNumber *theOpen;							
         
        theOpen = [NSDecimalNumber decimalNumberWithString:s_open];
        
        NSDecimalNumber *theHigh = [NSDecimalNumber decimalNumberWithString:s_high];
        NSDecimalNumber *theLow = [NSDecimalNumber decimalNumberWithString:s_low];
        NSDecimalNumber *theClose = [NSDecimalNumber decimalNumberWithString:lastprice];
        NSDecimalNumber *theVolume ;
        if ([volume_yahoo hasSuffix:@"M"]) {
            //有百萬字串
            theVolume= [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%f",[ [volume_yahoo stringByReplacingOccurrencesOfString:@"M" withString:@"" ] floatValue]*1000000 ]  ]; 
        }
        else if ([volume_yahoo hasSuffix:@"B"]) {
            //有十億字串
            theVolume= [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%f",[ [volume_yahoo stringByReplacingOccurrencesOfString:@"B" withString:@"" ] floatValue]*1000000000 ]  ]; 
        }
        else{
            theVolume= [NSDecimalNumber decimalNumberWithString:[volume_yahoo stringByReplacingOccurrencesOfString:@"," withString:@""]];
        } 
        
        //isYahooDailyDataOK=YES;								
        //3.最後一根Ｋ線資料與下載最新一筆資料比較
        if ([theLow compare:wLow] == NSOrderedAscending )  {
            wLow = theLow;
        }
        if ( [theHigh compare:wHigh] == NSOrderedDescending ) {
            wHigh= theHigh;
        }	
        wclose=theClose;							
        
        if (useTabelQuoteAddInstry==YES) {
            
            //4.替換 financialData 中的最新的及時資料
            if ([self Date_month:theDate] == [self Date_month:lastday]) {
                //表是在一週內 所以用替換
                //如何替換 financialData 中的資料
                NSLog(@"表是在一週內 所以用替換");
                NSLog(@"open=%0.02f high=%0.02f low=%0.02f close=%0.02f volume=%0.0f",[wOpen floatValue],[wHigh floatValue],[wLow floatValue],[wclose floatValue],[wvolume floatValue]);
                
                NSMutableDictionary *fData ;
                fData=  [[financialData objectAtIndex:[financialData count]-1 ] mutableCopy]   ;
                
                [fData setObject:wHigh forKey:@"high"];
                [fData setObject:wLow forKey:@"low"]; 
                [fData setObject:wclose forKey:@"close"];	
                [fData setObject:wclose forKey:@"adjClose"];					
                [(NSMutableArray *)financialData replaceObjectAtIndex:[financialData count]-1  withObject:fData];
                
                [fData release];
                
            }
            else {
                //表示跨週需要新增 
                NSLog(@"表示跨週需要新增");							
                //新增
                NSMutableDictionary *xcsvDict ;
                xcsvDict= [[NSMutableDictionary alloc] init];
                //[xcsvDict autorelease];							 
                [xcsvDict setObject:theDate forKey:@"date"];	
                [xcsvDict setObject:theOpen forKey:@"open"];
                [xcsvDict setObject:theHigh forKey:@"high"];
                [xcsvDict setObject:theLow forKey:@"low"];    
                [xcsvDict setObject:theClose forKey:@"close"];
                [xcsvDict setObject:theVolume forKey:@"volume"];
                [xcsvDict setObject:theClose forKey:@"adjClose"];
                [(NSMutableArray *)financialData addObject: xcsvDict  ];	
                
                [xcsvDict release];
                
                
                
                
            }		        }
        
             						
            
        [self afterDownloadYahooDailyData];
            
       
        
        
        
        
        
    }    
    
    
		
}

#pragma mark -
#pragma mark 6.日資料下載結束
-(void)afterDownloadYahooDailyData{
	NSLog(@"afterDownloadYahooDailyData_start");
	 
	 
	
		 
	//將資料進行還權動作======
	NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];				
	if ([(NSString *)[prefs  objectForKey:@"isUseAfterStockSplit" ] isEqualToString:@"Y"]) {
		
		float open,high,low,close ,adjclose;
		
		for (int i=0; i<[financialData count]; i++) {
			
			NSMutableDictionary *fData = (NSMutableDictionary *)[financialData objectAtIndex:i];		 
			close=[[fData objectForKey:@"close"] floatValue];		 
			open=[[fData objectForKey:@"open"] floatValue];		 
			high=[[fData objectForKey:@"high"] floatValue];		 
			low=[[fData objectForKey:@"low"] floatValue];		 
			//volume=[[fData objectForKey:@"volume"] floatValue];		 
			adjclose=[[fData objectForKey:@"adjClose"] floatValue];			
			
			float ratio;
			ratio=adjclose/close;
			close=ratio *close;
			open=ratio  *open;
			high=ratio  *high;
			low=ratio   *low;	
			
			NSDecimalNumber *theOpen = [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%0.03f",open]];
			[fData setObject:theOpen forKey:@"open"];
			NSDecimalNumber *theHigh = [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%0.03f",high]];
			[fData setObject:theHigh forKey:@"high"];
			NSDecimalNumber *theLow = [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%0.03f",low]];
			[fData setObject:theLow forKey:@"low"];    
			NSDecimalNumber *theClose = [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%0.03f",close]];
			[fData setObject:theClose forKey:@"close"];	
			
		}
		
		
		
	
	
	}
	 	
		 
	//=======================
	
	if (getYahooHistroryData_drawChart) {
		// 進入計算指標 與繪圖階段========
		//計算指標
		[self Caluate];
		
		//繪圖
		NSLog(@"[self.delgete StartDrawGraph:");
        [self.delgete StartDrawGraph:graph_index 
					isusdNavagarator:getYahooHistroryData_isuse_navcontroller 
				isresetGraphLocation:getYahooHistroryData_resetGraphLocation];
		//=============================
	}
	 

	if (getYahooHistroryData_isOptimizeTradeSystem==YES) {
		//是否進行最佳化
		[self Caluate_TradeSystem:@"MM3"];	//多參數的計算 是用來多股票的參數產生因此需要儲存記憶體 且刪除記憶體
	}
    else{
     	//不進行最佳化
       
        if (getYahooHistroryData_isCaluateTableIndicator==YES) {
            NSLog(@"開始進行CaluateTableIndicator=%@",symbol);
            [self Caluate_TableIndicator];
        }
        
        [self.delgete DelgetestopAnimating];    
    
    }
    
	
	
    //標記:繪圖結束後的最後位置 3.DataObject.m-afterDownloadYahooDailyData	    
	NSLog(@"afterDownloadYahooDailyData_end");	
}
#pragma mark -
#pragma mark  Yahoo ticker與Google ticker轉換
//標記:Yahoo ticker與Google ticker轉換 StockTableQuoteCell.m

//從yahoo 轉成 google
-(NSString *)TickerConvert_yahoo_google:(NSString *)yahoo_ticker{
    if (yahoo_ticker!=nil) {
        
        NSArray * code_array=[yahoo_ticker componentsSeparatedByString:@"."];        
        
        //標記:Add Target need Program
        
        if ([code_array count]==1) {
            //美國    
            return yahoo_ticker;
        }
        else if ([code_array count]==2) {
            //非美國
            //GOOGLE
            if ([[code_array objectAtIndex:1] isEqualToString:@"HK"]) {
                //香港
                return [NSString stringWithFormat:@"%@:%@",@"HKG",[code_array objectAtIndex:0]];                
                
            }
            else if ([[code_array objectAtIndex:1] isEqualToString:@"TW"] || [[code_array objectAtIndex:1] isEqualToString:@"TWO"] ) {
                //台灣                
                return [NSString stringWithFormat:@"%@:%@",@"TPE",[code_array objectAtIndex:0]];                
                
            }    
            else if ([[code_array objectAtIndex:1] isEqualToString:@"AX"]) {
                //澳洲
                return [NSString stringWithFormat:@"%@:%@",@"ASX",[code_array objectAtIndex:0]];                
                
            }
            else if ([[code_array objectAtIndex:1] isEqualToString:@"SS"] ) {
                //中國 上海               
                return [NSString stringWithFormat:@"%@:%@",@"SHA",[code_array objectAtIndex:0]];                
                
            }                
            else if ([[code_array objectAtIndex:1] isEqualToString:@"SZ"] ) {
                //中國 深圳                
                return [NSString stringWithFormat:@"%@:%@",@"SHE",[code_array objectAtIndex:0]];                
                
            }  
            else if ([[code_array objectAtIndex:1] isEqualToString:@"TO"]  ) {
                //加拿大                
                return [NSString stringWithFormat:@"%@:%@",@"TSE",[code_array objectAtIndex:0]];                
                
            } 
            else if ([[code_array objectAtIndex:1] isEqualToString:@"V"]  ) {
                //加拿大                
                return [NSString stringWithFormat:@"%@:%@",@"CVE",[code_array objectAtIndex:0]];                
                
            } 
            
            else if ([[code_array objectAtIndex:1] isEqualToString:@"NS"] ) {
                //印度               
                return [NSString stringWithFormat:@"%@:%@",@"NSE",[code_array objectAtIndex:0]];                
                
            }                
            else if ([[code_array objectAtIndex:1] isEqualToString:@"BO"] ) {
                //印度                
                return [NSString stringWithFormat:@"%@:%@",@"NSE",[code_array objectAtIndex:0]];                
                //雖然雅虎用BO 但是google
            }          
            else if ([[code_array objectAtIndex:1] isEqualToString:@"BE"] || [[code_array objectAtIndex:1] isEqualToString:@"BM"]  || [[code_array objectAtIndex:1] isEqualToString:@"DU"] || [[code_array objectAtIndex:1] isEqualToString:@"F"]  || [[code_array objectAtIndex:1] isEqualToString:@"HM"] || [[code_array objectAtIndex:1] isEqualToString:@"HA"] || [[code_array objectAtIndex:1] isEqualToString:@"MU"] || [[code_array objectAtIndex:1] isEqualToString:@"SG"] || [[code_array objectAtIndex:1] isEqualToString:@"DE"] ) {
                //德國  目前看來僅有 Deutsche Börse XETRA  電子交易所可以用         
                return [NSString stringWithFormat:@"%@:%@",@"ETR",[code_array objectAtIndex:0]];                
                
            } 
            else if ([[code_array objectAtIndex:1] isEqualToString:@"KS"] ) {
                //韓國                
                return [NSString stringWithFormat:@"%@:%@",@"SEO",[code_array objectAtIndex:0]];                
                
            }              
            else if ([[code_array objectAtIndex:1] isEqualToString:@"KQ"] ) {
                //韓國                
                return [NSString stringWithFormat:@"%@:%@",@"KDQ",[code_array objectAtIndex:0]];                
                
            }  
            else if ([[code_array objectAtIndex:1] isEqualToString:@"NZ"] ) {
                //紐西蘭                
                return [NSString stringWithFormat:@"%@:%@",@"NZE",[code_array objectAtIndex:0]];                
                
            }               
            else if ([[code_array objectAtIndex:1] isEqualToString:@"PA"] || [[code_array objectAtIndex:1] isEqualToString:@"NX"] ) {
                //法國                
                return [NSString stringWithFormat:@"%@:%@",@"EPA",[code_array objectAtIndex:0]];                
                
            }               
            else if ([[code_array objectAtIndex:1] isEqualToString:@"SA"] ) {
                //巴西                
                return [NSString stringWithFormat:@"%@:%@",@"SAO",[code_array objectAtIndex:0]];                
                
            }              
            else if ([[code_array objectAtIndex:1] isEqualToString:@"MX"] ) {
                //墨西哥  尚未有報價              
                return [NSString stringWithFormat:@"%@:%@",@"MXK",[code_array objectAtIndex:0]];                
                
            }  
            else if ([[code_array objectAtIndex:1] isEqualToString:@"SI"] ) {
                //新加坡  尚未有報價            
                return [NSString stringWithFormat:@"%@:%@",@"SIN",[code_array objectAtIndex:0]];                
                
            }             
            else if ([[code_array objectAtIndex:1] isEqualToString:@"L"] ) {
                //英國  有報價         
                return [NSString stringWithFormat:@"%@:%@",@"LON",[code_array objectAtIndex:0]];                
                
            }                 
            
            else{
                return [code_array objectAtIndex:0];
            }
            
            
            
        }
        else{
            return @"";
            
        }
    }
    else{
        
        return  @"";
        
    }
}


#pragma mark -
#pragma mark Google資料 歷史資料 日線 週線

//標記:將三個英文字母的月份轉為數字
-(int)MMM_MonthConvertToInterger:(NSString *)mmm{
    NSString *MMMs;
    MMMs=[mmm uppercaseString];
    if ([MMMs isEqualToString:[@"Jan" uppercaseString] ]) {
        return 1;
    }
    else if ([MMMs isEqualToString:[@"Feb" uppercaseString] ]) {
        return 2;
    }  
    else if ([MMMs isEqualToString:[@"Mar" uppercaseString] ]) {
        return 3;
    }  
    else if ([MMMs isEqualToString:[@"Apr" uppercaseString] ]) {
        return 4;
    }  
    else if ([MMMs isEqualToString:[@"May" uppercaseString] ]) {
        return 5;
    }  
    else if ([MMMs isEqualToString:[@"Jun" uppercaseString] ]) {
        return 6;
    }  
    else if ([MMMs isEqualToString:[@"Jul" uppercaseString] ]) {
        return 7;
    } 
    else if ([MMMs isEqualToString:[@"Aug" uppercaseString] ]) {
        return 8;
    }  
    else if ([MMMs isEqualToString:[@"Sep" uppercaseString] ]) {
        return 9;
    }  
    else if ([MMMs isEqualToString:[@"Oct" uppercaseString] ]) {
        return 10;
    }      
    else if ([MMMs isEqualToString:[@"Nov" uppercaseString] ]) {
        return 11;
    }  
    else if ([MMMs isEqualToString:[@"Dec" uppercaseString] ]) {
        return 12;
    }  
    else{
        return 0;
        
    }
    
}

//將google的日線資料全部取出 因為取出某一段時間 因為googl的日線資料僅可以取出200天 所以分段取出
-(NSMutableArray *)Google_HistoryData_Daily:(NSString *)symbols 
                                 StartDates:(NSString *)ST
                                   EndDates:(NSString *)ED{
    
    NSMutableArray *google_data_array;
    
    //google的每次取出資料限制
    int max_get;
    max_get=200;
    
    google_data_array=[[[NSMutableArray alloc] init] autorelease];
    
    int pre_count;
    pre_count=-1;
    
    BOOL looprun;
    looprun=YES;
    
    for (int i=0; i<30 && looprun==YES ; i++) {
        
        google_data_array=[self Google_HistoryData:google_data_array 
                                            Symbol:symbols
                                         StartDate: ST
                                           EndDate: ED
                                               num:max_get 
                                             start:0+i*max_get]; 
        
        if (pre_count==[google_data_array count]) {
            looprun=NO;
        }
        pre_count=[google_data_array count];
        
    }
    
    
    
    int index;
    index=0;
    
    NSMutableArray *out_array;
    out_array=[[[NSMutableArray alloc] init] autorelease];
    for (NSMutableDictionary *d in google_data_array) {
        
        NSArray * Times_array=[[d objectForKey:@"date"] componentsSeparatedByString:@","];        
        
        NSString *outs=nil;
        
        NSArray * MMM_array=[[Times_array objectAtIndex:0] componentsSeparatedByString:@" "]; 
        
        if ([MMM_array count]>1) {
           // NSLog(@"%i-%i-%i",[ self MMM_MonthConvertToInterger: [MMM_array objectAtIndex:0]],[[MMM_array objectAtIndex:1] intValue] ,[[Times_array objectAtIndex:1] intValue]   );
            
            
            
            outs=[ NSString stringWithFormat:@"%i-%i-%i,%0.2f,%0.2f,%0.2f,%0.2f,%i,%0.2f" ,[[Times_array objectAtIndex:1] intValue] , [ self MMM_MonthConvertToInterger: [MMM_array objectAtIndex:0]], [[MMM_array objectAtIndex:1] intValue]    , [[d objectForKey:@"open"] floatValue] , [[d objectForKey:@"high"] floatValue],[ [d objectForKey:@"low"] floatValue],[[d objectForKey:@"close"] floatValue] , [ [[d objectForKey:@"volume"] stringByReplacingOccurrencesOfString:@"," withString:@""] intValue] ,[[d objectForKey:@"close"] floatValue]  ];
        }
        
        //NSLog(@"%@",outs); 
        
        [out_array addObject:outs];
         
        
        index=index+1;
    }
    
    
   
    
    return  out_array;
    
}
//取出某一段時間 因為googl的日線資料僅可以取出200天 所以分段取出
-(NSMutableArray *)Google_HistoryData:(NSMutableArray *)google_data 
                               Symbol:(NSString *)symbol_s 
                            StartDate:(NSString *)StartDate_s 
                              EndDate:(NSString *)EndDate_s 
                                  num:(int)num_i 
                                start:(int) start_i {
    
    NSString *urls;
    if ([dwm isEqualToString: @"m"]) {
        urls=[NSString stringWithFormat:@"http://www.google.com/finance/historical?q=%@&startdate=%@&enddate=%@&num=%i&start=%i&histperiod=weekly",symbol_s,StartDate_s,EndDate_s,num_i,start_i] ; 
        
        
    }
    else if ([dwm isEqualToString: @"w"]){
          urls=[NSString stringWithFormat:@"http://www.google.com/finance/historical?q=%@&startdate=%@&enddate=%@&num=%i&start=%i&histperiod=weekly",symbol_s,StartDate_s,EndDate_s,num_i,start_i] ; 
    }
    else{
        urls=[NSString stringWithFormat:@"http://www.google.com/finance/historical?q=%@&startdate=%@&enddate=%@&num=%i&start=%i",symbol_s,StartDate_s,EndDate_s,num_i,start_i] ;      
    }
    
         
    
    NSLog(@"url=%@",urls);
    
    NSURL *  urla;
    urla = [NSURL URLWithString:urls];
    
    NSError * errorq = nil;
    NSString * download_string;
    download_string=[NSString stringWithContentsOfURL:urla encoding:NSASCIIStringEncoding error:&errorq];
    
    //NSLog(@"download_string=%@",download_string);
    
    NSError *error = nil;
    
    NSString *html;
    html=download_string;
    
    HTMLParser *rawparser = [[[HTMLParser alloc] initWithString:html error:&error] autorelease];
    
    if (error) {
        NSLog(@"Error: %@", error);
        return google_data;
    }
   
    
    HTMLNode *rawbodyNode = [rawparser body];
         
    
    //找出列  節點的開頭是tr
    NSArray *RawNodes = [rawbodyNode findChildTags:@"table"];
    int raw=1;
    for (HTMLNode *rawNode in RawNodes) {
        if ([[rawNode getAttributeNamed:@"class"] isEqualToString:@"gf-table historical_price"] ) {
            // NSLog(@"找到列的原始資料表格");
            //針對每個列 拆出行 column
            
            HTMLParser *columnparser = [[HTMLParser alloc] initWithString:[rawNode rawContents] error:&error];
            HTMLNode *columnbodyNode = [columnparser body];
            //找出行  節點的開頭是td           
            NSArray *ColumnNodes = [columnbodyNode findChildTags:@"td"]; 
            
            int column;
            
            NSMutableDictionary *tempa=nil;
            
            for (HTMLNode *rawNode_line in ColumnNodes) {
                //日期
                if ([[rawNode_line getAttributeNamed:@"class"] isEqualToString:@"lm"] )  {
                    
                    tempa=[[NSMutableDictionary alloc] init]; 
                    column=1;                      
                    
                    [tempa setObject:[rawNode_line contents] forKey:@"date"];
                    
                    //  NSLog(@"date=%@",[rawNode_line contents]);
                    
                    
                }   
                //報價
                if ([[rawNode_line getAttributeNamed:@"class"] isEqualToString:@"rgt"] )  {
                    
                    switch (column) {
                        case 1:{
                            // NSLog(@"open= %@" ,[rawNode_line contents]);
                            [tempa setObject:[rawNode_line contents] forKey:@"open"];                            
                            break;
                        }
                        case 2:{
                            //  NSLog(@"high= %@" ,[rawNode_line contents]);
                            [tempa setObject:[rawNode_line contents] forKey:@"high"];                            
                            break;
                        }  
                        case 3:{
                            // NSLog(@"low= %@" ,[rawNode_line contents]);
                            [tempa setObject:[rawNode_line contents] forKey:@"low"];                            
                            break;
                        }  
                        case 4:{
                            // NSLog(@"close= %@" ,[rawNode_line contents]);
                            [tempa setObject:[rawNode_line contents] forKey:@"close"];                            
                            
                            break;
                        }  
                            
                            
                            
                        default:
                            break;
                    }
                    
                    column=column+1;                     
                }    
                //成交量
                if ([[rawNode_line getAttributeNamed:@"class"] isEqualToString:@"rgt rm"] )  {
                    
                    //NSLog(@"volume=%@",[rawNode_line contents]);
                    NSObject *te=[rawNode_line contents];
                    [tempa setObject:te forKey:@"volume"];
                    
                    [google_data addObject:tempa];
                    column=1;
                    [tempa release];
                    tempa=nil;
                    
                }                   
                
                
            }             
            
            
            
            
            [columnparser release];                 
            
            
            
            
            raw=raw+1;
        }
        
        else{
            //  NSLog(@"不是列的原始資料=%@", [rawNode rawContents]);             
            
        }
        
    }
    
            
    
    
    
    
    return google_data;
}





#pragma mark -
#pragma mark 計算技術指標

-(void)Caluate{
	NSLog(@"caluate_start");
	
	//NSAutoreleasePool *pool=[[NSAutoreleasePool alloc] init];
	
	
    //初始化 參數 取出參數 參數是存在  aParaObject 物件內
	 
    if (aParaObject!=nil) {
        int ir;
        ir=[aParaObject retainCount];
        for (int j=0; j<ir; j++) {
            [aParaObject release];
        }
        
    }
    //NSLog(@"aParaObject retain count=%i",[aParaObject retainCount]);    
    
	aParaObject= [[ParaObject alloc] initWithTargetSymbol:symbol dwm:dwm] ;	
	
	//初始化技術指標紀錄內容 
	if (financialData_Calcuate!=nil) {
        
         [financialData_Calcuate release];
         financialData_Calcuate=nil;
    }
   
	 
    financialData_Calcuate	=[[NSMutableArray alloc] init];	
	
	
	//取出原始資料
	float open,high,low,close,volume;
	float close_1;//,open_1 ,high_1,low_1,volume_1;
	close_1=0;
    NSDate *cdate;
	//[cdate autorelease];
	//笑傲曲線通用變數
	float average1_1;
	average1_1=0;
	// 笑傲曲線內部計算參數物件
	NSMutableArray *LF_Array_temp;
	LF_Array_temp=[[NSMutableArray alloc] init];
	
	for (int k=0;k < [[aParaObject CaArray_LF] count]  ; k++) {
		LFcaluateTemp *LFcalcuate;
		LFcalcuate=[[LFcaluateTemp alloc] init];
		
		[LF_Array_temp addObject: LFcalcuate   ];
		[LFcalcuate release];
	}
	
	//如果Ｋ線太短 低於30 則不計算計數指標
    //[LF_Array_temp release];
	if ([financialData count]<2) {
		UIAlertView *al;
		al=[[UIAlertView alloc] initWithTitle:@"Caluate" message:@"K Bar number is too Short" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil];
		[al show];
        [al release];
		return;
	}
	
	
	//xMESA  陣列變數上
	
	int array_account;
	array_account= [financialData count]+ 30;
	
	float FastLim,SlowLim;
	
	float Smooth[array_account];
	float price[array_account];
	float Detrender[array_account];
	float Period[array_account];
	float Q1[array_account];
	float l1[array_account];
	float jl[array_account];
	float jQ[array_account];
	float l2[array_account];
	float Q2[array_account];
	float Re[array_account];
	float lm[array_account];
	float SmoothPeriod[array_account];
	float Phase[array_account];
	float DeltaPhase[array_account];
	float alpha[array_account];
	float MAMA[array_account];
	float FAMA[array_account];
	
	//===================
	float xFastLim,xSlowLim;
	
	float xSmooth[array_account];
	float xprice[array_account];
	float xDetrender[array_account];
	float xPeriod[array_account];
	float xQ1[array_account];
	float xl1[array_account];
	float xjl[array_account];
	float xjQ[array_account];
	float xl2[array_account];
	float xQ2[array_account];
	float xRe[array_account];
	float xlm[array_account];
	float xSmoothPeriod[array_account];
	float xPhase[array_account];
	float xDeltaPhase[array_account];
	float xalpha[array_account];
	float xMAMA[array_account];
	float xFAMA[array_account];	
	
	//歷史股價陣列
	float aclose[array_account];
	float aopen[array_account];	
	float ahigh[array_account];	
	float alow[array_account];
	float avol[array_account];	
	
	//KD 指標陣列
	float aRSV[array_account];
	float aKvalue[array_account];
	float aDvalue[array_account];
	
	NSMutableArray *nnk;
	nnk=[aParaObject CaArray_KD];
	if ([[[nnk objectAtIndex:0] valueForKey:@"isShow"] boolValue] ) {	
		for (int i=0; i<[financialData count]+30; i++) {
			aRSV[i]=0;
			aKvalue[i]=0;
			aDvalue[i]=0;
			
		}
	}
	
	
	
	//陣列變數歸0
	
	NSMutableArray *nnn;
	nnn=[aParaObject CaArray_xMESA];
	if ([[[nnn objectAtIndex:0] valueForKey:@"isShow"] boolValue] ) {	
		for (int i=0; i<[financialData count]+30; i++) {
			Smooth[i]=0;
			price[i]=0;
			Detrender[i]=0;
			Period[i]=0;
			Q1[i]=0;	 
			MAMA[i]=0;
			FAMA[i]=0;
		}
	}
	
	if ([[[nnn objectAtIndex:1] valueForKey:@"isShow"] boolValue] ) {
		for (int i=0; i<[financialData count]+3000; i++) {
			xSmooth[i]=0;
			xprice[i]=0;
			xDetrender[i]=0;
			xPeriod[i]=0;
			xQ1[i]=0;	 
			xMAMA[i]=0;
			xFAMA[i]=0;		
			
		}	
	}	
	
	
    //csvDict= [[NSMutableDictionary alloc] init];
	for (int i=0; i<[financialData count]; i++) {
		//初始化紀錄物件
		// NSAutoreleasePool *pool1=[[NSAutoreleasePool alloc] init];
		 //[csvDict autorelease];
        NSMutableDictionary *csvDict ;        
        csvDict= [[NSMutableDictionary alloc] init];
        //[pool1 release];
		
		//取出每日資料 
		{
			
			NSDictionary *fData = (NSDictionary *)[financialData objectAtIndex:i];		 
			close=[[fData objectForKey:@"close"] floatValue];		 
			open=[[fData objectForKey:@"open"] floatValue];		 
			high=[[fData objectForKey:@"high"] floatValue];		 
			low=[[fData objectForKey:@"low"] floatValue];		 
			volume=[[fData objectForKey:@"volume"] floatValue];		 
			cdate= [fData objectForKey:@"date"];  
			
			aclose[i]=close;
			alow[i]=low;
			ahigh[i]=high;
			aopen[i]=open;
			avol[i]=volume;
			
		}
		//取出前日資料 
		{
		    if (i>=1) {
				NSDictionary *fData = (NSDictionary *)[financialData objectAtIndex:i-1];		 
				close_1=[[fData objectForKey:@"close"] floatValue];		 
				//open_1=[[fData objectForKey:@"open"] floatValue];		 
				//high_1=[[fData objectForKey:@"high"] floatValue];		 
				//low_1=[[fData objectForKey:@"low"] floatValue];		 
				//volume_1=[[fData objectForKey:@"volume"] floatValue];		 
				
		    }
			
		}	
		
		
		//指標 移動均線 上=========== 
		float average1 ;
		
	    //參數物件下的移動均線參數
		//averag1 主要計算給笑傲曲線使用
		average1=[self MovingAverage_record:csvDict index_i:i N_Indentfy:@"usedforLF" P_movingday:5 I_close:close];
		
		//移動均線
		NSMutableArray *aaa;
		aaa=[aParaObject CaArray_MovingAverage];
		for (int j=0; j<[aaa count]; j++) {
		    if([[[aaa objectAtIndex:j] valueForKey:@"isShow"] boolValue]){
				 
                [self MovingAverage_record:csvDict index_i:i N_Indentfy:[[aaa objectAtIndex:j] valueForKey:@"idendfiler"] P_movingday:[[[aaa objectAtIndex:j] valueForKey:@"movingday"] intValue] I_close:close];
			}
		}
		
		//指標 移動均線 下========== 
		
		//指標 笑傲線 上=================
		NSMutableArray *bbb;
		bbb=[aParaObject CaArray_LF];
		for (int j=0; j<[bbb count]; j++) {
		    if([[[bbb objectAtIndex:j] valueForKey:@"isShow"] boolValue]){
				
				//LFcaluateTemp *ltemp;
				
				//ltemp=[ LF_Array_temp  objectAtIndex:j];
				//NSLog(@"LF 參數BRangeDay=%i SRangeDay=%i Bratio=%0.03f Sratio=%0.03f",[[[bbb objectAtIndex:j] valueForKey:@"BRangeDay"] intValue],[[[bbb objectAtIndex:j] valueForKey:@"SRangeDay"] intValue],[[[bbb objectAtIndex:j] valueForKey:@"Bratio"] floatValue],[[[bbb objectAtIndex:j] valueForKey:@"Sratio"] floatValue]);
				
				[self LF_record:csvDict
						index_i:i 
					 N_Indentfy:[[bbb objectAtIndex:j] valueForKey:@"idendfiler"]
					P_BRangeDay:[[[bbb objectAtIndex:j] valueForKey:@"BRangeDay"] intValue] 
					P_SRangeDay:[[[bbb objectAtIndex:j] valueForKey:@"SRangeDay"] intValue]
					   P_Bratio:[[[bbb objectAtIndex:j] valueForKey:@"Bratio"] floatValue]
					   P_Sratio:[[[bbb objectAtIndex:j] valueForKey:@"Sratio"] floatValue] 
					 I_average1:average1 
				   I_average1_1:average1_1 
						I_close:close 
						 I_high:high 
						  I_low:low 
					  I_close_1:close_1 
					  O_LFCtemp:[ LF_Array_temp  objectAtIndex:j]];
				
				
				
				
				
			}
		}
		//[bbb release];
		//指標 笑傲線 下=================
        
		//MESA 利用NSMutableArray 上
	    NSMutableArray *ddd;
		ddd=[aParaObject CaArray_MESA];
		for (int j=0; j<[ddd count]; j++) {
		    if([[[ddd objectAtIndex:j] valueForKey:@"isShow"] boolValue]){
				
				[self MESA_record:csvDict 
						  index_i:i 
					   N_Indentfy:[[ddd objectAtIndex:j] valueForKey:@"idendfiler"] 
						P_FastLim:[[[ddd objectAtIndex:j] valueForKey:@"FastLim"] floatValue] 
						P_SlowLim:[[[ddd objectAtIndex:j] valueForKey:@"SlowLim"] floatValue] 
							fhigh:high 
							 flow:low];
				
				
			}
		}
  	    //MESA 利用NSMutableArray 下	
		
		//ＭＥＳＡ 利用Ｃ＋＋的陣列
		NSMutableArray *eee;
		eee=[aParaObject CaArray_xMESA];
	    if (i>=10 && [[[eee objectAtIndex:0] valueForKey:@"isShow"] boolValue] ) {
			//   NSLog(@"mesa0  s=======");
			
			FastLim=[[[eee objectAtIndex:0] valueForKey:@"FastLim"] floatValue];
			SlowLim=[[[eee objectAtIndex:0] valueForKey:@"SlowLim"] floatValue];			
			
			price[i]=(high +low)/2;		
			Smooth[i] =(4 * price[i] + 3 * price[i-1] + 2 * price[i-2] + price[i-3])/10;
		 	
			Detrender[i]=(0.0962*Smooth[i]+0.5769*Smooth[i-2]-0.5769*Smooth[i-4]-0.0962*Smooth[i-6])*(0.075*Period[i-1]+0.54);
			Q1[i]=(0.0962*Detrender[i]+0.5769*Detrender[i-2]-0.5769*Detrender[i-4]-0.0962*Detrender[i-6])*(0.075*Period[i-1]+0.54);
			
			l1[i]=Detrender[i-3];
			jl[i]=(0.0962*l1[i]+0.5769*l1[i-2]-0.5769*l1[i-4]-.0962*l1[i-6])*(0.075*Period[i-1]+0.54);	
			jQ[i]=(0.0962*Q1[i]+.5769*Q1[i-2]-.5769*Q1[i-4]-0.0962*Q1[i-6])*(0.075*Period[i-1]+0.54) ;
			l2[i]=l1[i]-jQ[i];
			Q2[i]=Q1[i]+jl[i];
			
			l2[i]=0.2*l2[i]+0.8*l2[i-1];
			Q2[i]=0.2*Q2[i]+0.8*Q2[i-1];
			Re[i]=l2[i]*l2[i-1]+Q2[i]*Q2[i-1];
			lm[i]=l2[i]*Q2[i-1]-Q2[i]*l2[i-1];
			Re[i]=0.2*Re[i]+0.8*Re[i-1];
			lm[i]=0.2*lm[i]+0.8*lm[i-1];
			
			
			if( lm[i] !=0 && Re[i] !=0 )
			{
				Period[i]= 360/(atan((lm[i]/Re[i]))*180/(4*atan(1)));
				
			}
			
			
			
			if( Period[i]>1.5*Period[i-1])
				Period[i]=1.5*Period[i-1];
			
			if(Period[i]<0.67*Period[i-1])
				Period[i]=0.67*Period[i-1];
			
			if(Period[i]<6)
				Period[i]=6;
			if(Period[i]>50)
				Period[i]=50;
			
			Period[i]=0.2*Period[i]+0.8*Period[i-1];
			
			// [csvDict setObject:[NSNumber numberWithFloat:Period[i]] forKey: @"Period"];	
			
			SmoothPeriod[i]=0.33*Period[i]+0.67*SmoothPeriod[i-1];
			
			if( l1[i] !=0 )
				Phase[i]=atan(Q1[i]/l1[i])*180/(4*atan(1));
			
			DeltaPhase[i]=Phase[i-1]-Phase[i];
			if(DeltaPhase[i]<1)
				DeltaPhase[i]=1;
			alpha[i]=FastLim/DeltaPhase[i];
			
			if(alpha[i]<SlowLim)
				alpha[i]=SlowLim;
			
			if( alpha[i]>FastLim)
				alpha[i]=FastLim;
			
			
			MAMA[i]=alpha[i]*price[i]+(1-alpha[i])*MAMA[i-1];
			FAMA[i]=0.5*alpha[i]*MAMA[i]+(1-0.5*alpha[i])*FAMA[i-1];			
			
			//NSLog(@"MAMA=%@",MAMA[i]);
			
			// NSDecimalNumber *CMAMA = [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%0.3f",MAMA[i]]];		 
			[csvDict setObject:[NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%0.3f",MAMA[i]]] forKey:@"aCmesa1_mama"];	
			// NSDecimalNumber *CFAMA = [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%0.3f",FAMA[i]]];		 
			[csvDict setObject:[NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%0.3f",FAMA[i]]] forKey:@"aCmesa1_fama"];	
			//   NSLog(@"mesa0  e=======");		 			
			
		}
		else {
			// NSDecimalNumber *CMAMA = [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%0.3f",MAMA[i]]];		 
			[csvDict setObject:[NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%i",0]] forKey:@"aCmesa1_mama"];	
			// NSDecimalNumber *CFAMA = [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%0.3f",FAMA[i]]];		 
			[csvDict setObject:[NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%i",0]] forKey:@"aCmesa1_fama"];	
			//   NSLog(@"mesa0  e=======");					
			
		}
		
		
        if (i>=10 && [[[eee objectAtIndex:1] valueForKey:@"isShow"] boolValue]) {
			//NSLog(@"mesa1  s=======");
			xFastLim=[[[eee objectAtIndex:1] valueForKey:@"FastLim"] floatValue];
			xSlowLim=[[[eee objectAtIndex:1] valueForKey:@"SlowLim"] floatValue];			
			
			xprice[i]=(high +low)/2;		
			xSmooth[i] =(4 * xprice[i] + 3 * xprice[i-1] + 2 * xprice[i-2] + xprice[i-3])/10;
			
			//[csvDict setObject:[NSNumber numberWithFloat:Smooth[i]] forKey: @"Smooth"];	
			
			xDetrender[i]=(0.0962*xSmooth[i]+0.5769*xSmooth[i-2]-0.5769*xSmooth[i-4]-0.0962*xSmooth[i-6])*(0.075*xPeriod[i-1]+0.54);
			xQ1[i]=(0.0962*xDetrender[i]+0.5769*xDetrender[i-2]-0.5769*xDetrender[i-4]-0.0962*xDetrender[i-6])*(0.075*xPeriod[i-1]+0.54);
			
			xl1[i]=xDetrender[i-3];
			xjl[i]=(0.0962*xl1[i]+0.5769*xl1[i-2]-0.5769*xl1[i-4]-.0962*xl1[i-6])*(0.075*xPeriod[i-1]+0.54);	
			xjQ[i]=(0.0962*xQ1[i]+.5769*xQ1[i-2]-.5769*xQ1[i-4]-0.0962*xQ1[i-6])*(0.075*xPeriod[i-1]+0.54) ;
			xl2[i]=xl1[i]-xjQ[i];
			xQ2[i]=xQ1[i]+xjl[i];
			
			xl2[i]=0.2*xl2[i]+0.8*xl2[i-1];
			xQ2[i]=0.2*xQ2[i]+0.8*xQ2[i-1];
			xRe[i]=xl2[i]*xl2[i-1]+xQ2[i]*xQ2[i-1];
			xlm[i]=xl2[i]*xQ2[i-1]-xQ2[i]*xl2[i-1];
			xRe[i]=0.2*xRe[i]+0.8*xRe[i-1];
			xlm[i]=0.2*xlm[i]+0.8*xlm[i-1];
			
			
			if( xlm[i] !=0 && xRe[i] !=0 )
			{
				xPeriod[i]= 360/(atan((xlm[i]/xRe[i]))*180/(4*atan(1)));
				
			}
			
			
			
			if( xPeriod[i]>1.5*xPeriod[i-1])
				xPeriod[i]=1.5*xPeriod[i-1];
			
			if(xPeriod[i]<0.67*xPeriod[i-1])
				xPeriod[i]=0.67*xPeriod[i-1];
			
			if(xPeriod[i]<6)
				xPeriod[i]=6;
			if(xPeriod[i]>50)
				xPeriod[i]=50;
			
			xPeriod[i]=0.2*xPeriod[i]+0.8*xPeriod[i-1];
			
			//[csvDict setObject:[NSNumber numberWithFloat:Period[i]] forKey: @"Period"];	
			
			xSmoothPeriod[i]=0.33*xPeriod[i]+0.67*xSmoothPeriod[i-1];
			
			if( xl1[i] !=0 )
				xPhase[i]=atan(xQ1[i]/xl1[i])*180/(4*atan(1));
			
			xDeltaPhase[i]=xPhase[i-1]-xPhase[i];
			if(xDeltaPhase[i]<1)
				xDeltaPhase[i]=1;
			xalpha[i]=xFastLim/xDeltaPhase[i];
			
			if(xalpha[i]<xSlowLim)
				xalpha[i]=xSlowLim;
			
			if( xalpha[i]>xFastLim)
				xalpha[i]=xFastLim;
			
			
			xMAMA[i]=xalpha[i]*xprice[i]+(1-xalpha[i])*xMAMA[i-1];
			xFAMA[i]=0.5*xalpha[i]*xMAMA[i]+(1-0.5*xalpha[i])*xFAMA[i-1];			
			
			//NSDecimalNumber *CMAMA = [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%0.3f",xMAMA[i]]];		 
			[csvDict setObject: [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%0.3f",xMAMA[i]]] forKey:@"aCmesa2_mama"];	
			//NSDecimalNumber *CFAMA = [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%0.3f",xFAMA[i]]];		 
			[csvDict setObject:[NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%0.3f",xFAMA[i]]] forKey:@"aCmesa2_fama"];	
			
			///	NSLog(@"mesa1  e=======");
			
		}
		else {
			//NSDecimalNumber *CMAMA = [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%0.3f",xMAMA[i]]];		 
			[csvDict setObject: [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%i",0]] forKey:@"aCmesa2_mama"];	
			//NSDecimalNumber *CFAMA = [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%0.3f",xFAMA[i]]];		 
			[csvDict setObject:[NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%i",0]] forKey:@"aCmesa2_fama"];	
			
		}
		
		
		
		//ＭＥＳＡ 利用Ｃ＋＋的陣列 下
		
		//KD 指標上		
		NSMutableArray *KKK;
		KKK=[aParaObject CaArray_KD];
	    if ( [[[KKK objectAtIndex:0] valueForKey:@"isShow"] boolValue] ){
			
			
			//參數 
			int N,M1,M2;
			N=[[[KKK objectAtIndex:0] valueForKey:@"N"] floatValue]; 
			M1=[[[KKK objectAtIndex:0] valueForKey:@"M1"] floatValue];
			M2=[[[KKK objectAtIndex:0] valueForKey:@"M2"] floatValue];
			//最低價
			if (i>10) {
				
				float llv,hhv;
				
				llv=alow[i];
				for (int bi=0; bi<N; bi++) {
					if (llv>alow[i-bi]) {
						llv=alow[i-bi];
					}
				}
				hhv=ahigh[i];
				for (int bi=0; bi<N; bi++) {
					if (hhv<ahigh[i-bi]) {
						hhv=ahigh[i-bi];
					}
				}		
				aRSV[i]=(close-llv)/(hhv-llv)*100;	
				//NSLog(@"ffff=%f",aRSV[i]);
				aKvalue[i]=aRSV[i]/M1+aKvalue[i-1]*(M1-1)/M1;
				aDvalue[i]=aKvalue[i]/M2+aDvalue[i-1]*(M2-1)/M2;
				
				
				[csvDict setObject:[NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%0.3f",aKvalue[i]]] forKey:@"CKD_K"];	
				[csvDict setObject:[NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%0.3f",aDvalue[i]]] forKey:@"CKD_D"];				
				
				
			}
			else {
				[csvDict setObject:[NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%i",0]] forKey:@"CKD_K"];	
				[csvDict setObject:[NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%i",0]] forKey:@"CKD_D"];				
				
			}
			
			
			
			
			
			
		}		
		
		//KD 指標下	 
		
		//紀錄日期用
		[csvDict setObject:cdate forKey:@"Cdate"];			
		
		[csvDict setObject:[NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%0.3f",volume]] forKey:@"Volume"];		
		
		//後期通用作業區塊 上=============
		
		//設定前期資料使用
		if (i>=1) {
			average1_1=average1; //用於笑傲曲線 的第一根Ｋ線
		}
		
		//將資料存入 技術指標紀錄器內
		 [financialData_Calcuate addObject: csvDict   ];
		 [csvDict release];		 
		
		//後期通用作業區塊 下=============
	}
	
	//標記:將指標詳細內容計算結果寫入檔案中
	//[self CwriteToFile:[self CpathForSymbol:[self.symbol stringByAppendingString:dwm ]] atomically:YES];	
	
	//[cdate autorelease];
	
	[LF_Array_temp release];
	//[csvDict release];
    
   // [pool release];
	
	NSLog(@"caluate_end");
	
}


#pragma mark -
#pragma mark 計算報價指標
-(void)Caluate_TableIndicator{
	//NSLog(@"Caluate_TableIndicator=%i",[financialData count]);
	if ([havetocalcuateTableIndicator count]>0) {
		
        for (int i=0; i<[havetocalcuateTableIndicator count]; i++) {
		 
			if ([[havetocalcuateTableIndicator objectAtIndex:i] isEqualToString:NSLocalizedString(@"5Day Change%", @"5日漲跌幅")]   ) {
				if ([financialData count]>6) {
					float close1;
					float close6;
					
					NSDictionary *fData1 = (NSDictionary *)[financialData objectAtIndex:[financialData count]-1];		 
					close1=[[fData1 objectForKey:@"close"] floatValue];					
					NSDictionary *fData6 = (NSDictionary *)[financialData objectAtIndex:[financialData count]-6];		 
					close6=[[fData6 objectForKey:@"close"] floatValue];				
					
					if (close6>0) {
						ChangePercent5day=  [[NSString stringWithFormat:@"%0.02f", (close1-close6 )/close6*100 ] copy]  ;
					}
					
					
				}
										
			}
			if ([[havetocalcuateTableIndicator objectAtIndex:i] isEqualToString: NSLocalizedString(@"10Day Change%", @"10日漲跌幅")]   ) {
				if ([financialData count]>10) {
					float close1;
					float close10;
					
					NSDictionary *fData1 = (NSDictionary *)[financialData objectAtIndex:[financialData count]-1];		 
					close1=[[fData1 objectForKey:@"close"] floatValue];					
					NSDictionary *fData10 = (NSDictionary *)[financialData objectAtIndex:[financialData count]-11];		 
					close10=[[fData10 objectForKey:@"close"] floatValue];				
					
					if (close10>0) {
						ChangePercent10day=  [[NSString stringWithFormat:@"%0.02f", (close1-close10 )/close10*100 ] copy]  ;
					}
					
					
				}
			
			
			}		
			if ([[havetocalcuateTableIndicator objectAtIndex:i] isEqualToString: NSLocalizedString(@"20Day Change%", @"20日漲跌幅")]   ) {
				if ([financialData count]>20) {
					float close1;
					float close20;
					
					NSDictionary *fData1 = (NSDictionary *)[financialData objectAtIndex:[financialData count]-1];		 
					close1=[[fData1 objectForKey:@"close"] floatValue];					
					NSDictionary *fData20 = (NSDictionary *)[financialData objectAtIndex:[financialData count]-21];		 
					close20=[[fData20 objectForKey:@"close"] floatValue];				
					
					if (close20>0) {
						ChangePercent20day=  [[NSString stringWithFormat:@"%0.02f", (close1-close20 )/close20*100 ] copy]  ;
					}
					
					
				}			
			
			
			}		
			
			if ([[havetocalcuateTableIndicator objectAtIndex:i] isEqualToString: NSLocalizedString(@"60Day Change%", @"60日漲跌幅")]   ) {
				if ([financialData count]>60) {
					float close1;
					float close60;
					
					NSDictionary *fData1 = (NSDictionary *)[financialData objectAtIndex:[financialData count]-1];		 
					close1=[[fData1 objectForKey:@"close"] floatValue];					
					NSDictionary *fData60 = (NSDictionary *)[financialData objectAtIndex:[financialData count]-61];		 
					close60=[[fData60 objectForKey:@"close"] floatValue];				
					
					if (close60>0) {
						ChangePercent60day=  [[NSString stringWithFormat:@"%0.02f", (close1-close60 )/close60*100 ] copy]  ;
					}
					
					
				}			
				
				
			}		
			if ([[havetocalcuateTableIndicator objectAtIndex:i] isEqualToString: NSLocalizedString(@"120Day Change%", @"120日漲跌幅")]   ) {
				if ([financialData count]>120) {
					float close1;
					float close120;
					
					NSDictionary *fData1 = (NSDictionary *)[financialData objectAtIndex:[financialData count]-1];		 
					close1=[[fData1 objectForKey:@"close"] floatValue];					
					NSDictionary *fData120 = (NSDictionary *)[financialData objectAtIndex:[financialData count]-121];		 
					close120=[[fData120 objectForKey:@"close"] floatValue];				
					
					if (close120>0) {
						ChangePercent120day=  [[NSString stringWithFormat:@"%0.02f", (close1-close120 )/close120*100 ] copy]  ;
					}
					
					
				}			
				
				
			}		
			if ([[havetocalcuateTableIndicator objectAtIndex:i] isEqualToString: NSLocalizedString(@"240Day Change%", @"240日漲跌幅")]   ) {
				if ([financialData count]>240) {
					float close1;
					float close240;
					
					NSDictionary *fData1 = (NSDictionary *)[financialData objectAtIndex:[financialData count]-1];		 
					close1=[[fData1 objectForKey:@"close"] floatValue];					
					NSDictionary *fData240 = (NSDictionary *)[financialData objectAtIndex:[financialData count]-241];		 
					close240=[[fData240 objectForKey:@"close"] floatValue];				
					
					if (close240>0) {
						ChangePercent240day=  [[NSString stringWithFormat:@"%0.02f", (close1-close240 )/close240*100 ] copy]  ;
					}
					
					
				}			
				
				
			}		
			if ([[havetocalcuateTableIndicator objectAtIndex:i] isEqualToString: NSLocalizedString(@"Week Change%", @"週漲跌幅")]   ) {
				if ([financialData count]>240) {
					float close1;
					float closex;
					NSDictionary *fData1 = (NSDictionary *)[financialData objectAtIndex:[financialData count]-1];		 
					close1=[[fData1 objectForKey:@"close"] floatValue];					
					
					int weekday_0;
					int weekday_pre;
					
					NSDictionary *fDatax = (NSDictionary *)[financialData objectAtIndex:[financialData count]-1];		 
					NSDate *cdate;
					cdate= [fDatax objectForKey:@"date"];  						
					weekday_pre= [self Date_weekday:cdate  ]-1 ;
					closex=[[fDatax objectForKey:@"close"] floatValue];							
					
					for (int i=1 ;i<[financialData count]-2 ; i++) {
						
						fDatax = (NSDictionary *)[financialData objectAtIndex:[financialData count]-1-i];						
						cdate= [fDatax objectForKey:@"date"];  						
						weekday_0= [self Date_weekday:cdate  ]-1 ;						
						
						if (weekday_0>weekday_pre) {
							closex=[[fDatax objectForKey:@"close"] floatValue];							
							break;
						}
						weekday_pre=weekday_0;
					}
				 
					
					
					if (closex>0) {
						ChangePercentWeek= [  [NSString stringWithFormat:@"%0.02f",(close1- closex)/closex*100] copy]  ;
					}
					
					
				}			
				
				
			}		
			if ([[havetocalcuateTableIndicator objectAtIndex:i] isEqualToString: NSLocalizedString(@"Month Change%", @"月漲跌幅")]   ) {
				if ([financialData count]>240) {
					float close1;
					float closex;
					NSDictionary *fData1 = (NSDictionary *)[financialData objectAtIndex:[financialData count]-1];		 
					close1=[[fData1 objectForKey:@"close"] floatValue];					
					
					int month_0;
					int month_pre;
					
					NSDictionary *fDatax = (NSDictionary *)[financialData objectAtIndex:[financialData count]-1];		 
					NSDate *cdate;
					cdate= [fDatax objectForKey:@"date"];  						
					month_pre= [self Date_month:cdate  ]  ;
					closex=[[fDatax objectForKey:@"close"] floatValue];							
					
					for (int i=1 ;i<[financialData count]-2 ; i++) {
						fDatax = (NSDictionary *)[financialData objectAtIndex:[financialData count]-1-i];						
						cdate= [fDatax objectForKey:@"date"];  						
						month_0= [self Date_month:cdate  ]  ;						
						
						if (month_0!=month_pre) {
							closex=[[fDatax objectForKey:@"close"] floatValue];							
							break;
						}
						month_pre=month_0;
					}
					
					
					
					if (closex>0) {
						ChangePercentMonth= [  [NSString stringWithFormat:@"%0.02f",(close1- closex)/closex*100] copy] ;
					}
					
					
				}			
				
				
			}		
			if ([[havetocalcuateTableIndicator objectAtIndex:i] isEqualToString: NSLocalizedString(@"Quarter Change%", @"季漲跌幅")]   ) {
			 	if ([financialData count]>240) {
					float close1;
					float closex;
					NSDictionary *fData1 = (NSDictionary *)[financialData objectAtIndex:[financialData count]-1];		 
					close1=[[fData1 objectForKey:@"close"] floatValue];					
					
					int month_0;
					int month_pre;
					
					NSDictionary *fDatax = (NSDictionary *)[financialData objectAtIndex:[financialData count]-1];		 
					NSDate *cdate;
					cdate= [fDatax objectForKey:@"date"];  						
					month_pre= [self Date_month:cdate  ]  ;
					closex=[[fDatax objectForKey:@"close"] floatValue];							
					
					for (int i=1 ;i<[financialData count]-2 ; i++) {
						fDatax = (NSDictionary *)[financialData objectAtIndex:[financialData count]-1-i];						
						cdate= [fDatax objectForKey:@"date"];  						
						month_0= [self Date_month:cdate  ]  ;						
						
						if (month_0!=month_pre && (month_0==3 || month_0==6 || month_0==9 || month_0==12 )) {
							closex=[[fDatax objectForKey:@"close"] floatValue];							
							break;
						}
						month_pre=month_0;
					}
					
					
					
					if (closex>0) {
						ChangePercentQuarter=  [  [NSString stringWithFormat:@"%0.02f",(close1- closex)/closex*100] copy ] ;
					}
					
					
				}			
				
				
				
			}		
			if ([[havetocalcuateTableIndicator objectAtIndex:i] isEqualToString: NSLocalizedString(@"Year Change%", @"年漲跌幅")]   ) {
				if ([financialData count]>240) {
					float close1;
					float closex;
					NSDictionary *fData1 = (NSDictionary *)[financialData objectAtIndex:[financialData count]-1];		 
					close1=[[fData1 objectForKey:@"close"] floatValue];					
					
					int month_0;
					int month_pre;
					
					NSDictionary *fDatax = (NSDictionary *)[financialData objectAtIndex:[financialData count]-1];		 
					NSDate *cdate;
					cdate= [fDatax objectForKey:@"date"];  						
					month_pre= [self Date_month:cdate  ]  ;
					closex=[[fDatax objectForKey:@"close"] floatValue];							
					
					for (int i=1 ;i<[financialData count]-2 ; i++) {
						fDatax = (NSDictionary *)[financialData objectAtIndex:[financialData count]-1-i];						
						cdate= [fDatax objectForKey:@"date"];  						
						month_0= [self Date_month:cdate  ]  ;						
						
						if (month_0!=month_pre && month_0==12  ) {
							closex=[[fDatax objectForKey:@"close"] floatValue];							
							break;
						}
						month_pre=month_0;
					}
					
					
					
					if (closex>0) {
						ChangePercentYear=  [  [NSString stringWithFormat:@"%0.02f",(close1- closex)/closex*100] copy]  ;
					}
					
					
				}			
				
				
			}		
			if ([[havetocalcuateTableIndicator objectAtIndex:i] hasPrefix: NSLocalizedString(@"LF_Signal", @"LF_訊號")] || [[havetocalcuateTableIndicator objectAtIndex:i] hasPrefix: NSLocalizedString(@"LF_Break P", @"LF_關鍵價位")] || [[havetocalcuateTableIndicator objectAtIndex:i] hasPrefix: NSLocalizedString(@"LF_LongDay", @"LF_買入天數")]	|| [[havetocalcuateTableIndicator objectAtIndex:i] hasPrefix: NSLocalizedString(@"LF_ShortgProfit", @"LF_賣出獲利率")] || [[havetocalcuateTableIndicator objectAtIndex:i] hasPrefix: NSLocalizedString(@"LF_LongProfit", @"LF_買入獲利率")]	|| [[havetocalcuateTableIndicator objectAtIndex:i] hasPrefix: NSLocalizedString(@"LF_ShortgDay", @"LF_賣出天數")]|| [[havetocalcuateTableIndicator objectAtIndex:i] hasPrefix: NSLocalizedString(@"LF_Action", @"LF_動作")]) {
				
				
				
				
				
				NSMutableDictionary *csvDict ;
				
				int index_para;
				
				if ([[havetocalcuateTableIndicator objectAtIndex:i] isEqualToString: NSLocalizedString(@"LF_Signal1", @"LF_訊號1")]  ) {
				    index_para=0;
				}
				else if([[havetocalcuateTableIndicator objectAtIndex:i] isEqualToString: NSLocalizedString(@"LF_Signal2", @"LF_訊號2")]  ) {
					index_para=1;
				}
				else if([[havetocalcuateTableIndicator objectAtIndex:i] isEqualToString: NSLocalizedString(@"LF_Signal3", @"LF_訊號3")]  ) {
					index_para=2;
				}				
				else if([[havetocalcuateTableIndicator objectAtIndex:i] isEqualToString: NSLocalizedString(@"LF_Break P1", @"LF_關鍵價位1")]  ) {
					index_para=0;
				}	
				else if([[havetocalcuateTableIndicator objectAtIndex:i] isEqualToString: NSLocalizedString(@"LF_Break P2", @"LF_關鍵價位2")]  ) {
					index_para=1;
				}		
				else if([[havetocalcuateTableIndicator objectAtIndex:i] isEqualToString: NSLocalizedString(@"LF_Break P3", @"LF_關鍵價位3")]  ) {
					index_para=2;
				}					
				else if([[havetocalcuateTableIndicator objectAtIndex:i] isEqualToString: NSLocalizedString(@"LF_LongDay1", @"LF_買入天數1")]  ) {
					index_para=0;
				}
				else if([[havetocalcuateTableIndicator objectAtIndex:i] isEqualToString: NSLocalizedString(@"LF_LongDay2", @"LF_買入天數2")]  ) {
					index_para=1;
				}				
				else if([[havetocalcuateTableIndicator objectAtIndex:i] isEqualToString: NSLocalizedString(@"LF_LongDay3", @"LF_買入天數3")]  ) {
					index_para=2;
				}				
				else if([[havetocalcuateTableIndicator objectAtIndex:i] isEqualToString: NSLocalizedString(@"LF_ShortgDay1", @"LF_賣出天數1")]  ) {
					index_para=0;
				}				
				else if([[havetocalcuateTableIndicator objectAtIndex:i] isEqualToString: NSLocalizedString(@"LF_ShortgDay2", @"LF_賣出天數2")]  ) {
					index_para=1;
				}
				else if([[havetocalcuateTableIndicator objectAtIndex:i] isEqualToString: NSLocalizedString(@"LF_ShortgDay3", @"LF_賣出天數3")]  ) {
					index_para=2;
				}				
				else if([[havetocalcuateTableIndicator objectAtIndex:i] isEqualToString: NSLocalizedString(@"LF_LongProfit1", @"LF_買入獲利率1")]  ) {
					index_para=0;
				}					
				else if([[havetocalcuateTableIndicator objectAtIndex:i] isEqualToString: NSLocalizedString(@"LF_LongProfit2", @"LF_買入獲利率2")]  ) {
					index_para=1;
				}				
				else if([[havetocalcuateTableIndicator objectAtIndex:i] isEqualToString: NSLocalizedString(@"LF_LongProfit3", @"LF_買入獲利率3")]  ) {
					index_para=2;
				}	
				else if([[havetocalcuateTableIndicator objectAtIndex:i] isEqualToString: NSLocalizedString(@"LF_ShortgProfit1", @"LF_賣出獲利率1")]  ) {
					index_para=0;
				}				
				else if([[havetocalcuateTableIndicator objectAtIndex:i] isEqualToString: NSLocalizedString(@"LF_ShortgProfit2", @"LF_賣出獲利率2")]  ) {
					index_para=1;
				}					
				else if([[havetocalcuateTableIndicator objectAtIndex:i] isEqualToString: NSLocalizedString(@"LF_ShortgProfit3", @"LF_賣出獲利率3")]  ) {
					index_para=2;
				}	
				else if([[havetocalcuateTableIndicator objectAtIndex:i] isEqualToString: NSLocalizedString(@"LF_Action1", @"LF_動作1")]  ) {
					index_para=0;
				}				
				else if([[havetocalcuateTableIndicator objectAtIndex:i] isEqualToString: NSLocalizedString(@"LF_Action2", @"LF_動作2")]  ) {
					index_para=1;
				}
				else if([[havetocalcuateTableIndicator objectAtIndex:i] isEqualToString: NSLocalizedString(@"LF_Action1", @"LF_動作3")]  ) {
					index_para=2;
				}				
				
				
				//原始資料變數區
				float high,low,close ;
				float close_1;//open_1,high_1,low_1,close_1,volume_1,adjclose_1;				
			 
				//笑傲曲線通用變數
				float average1_1;					
				float LF_bout,LF_sout;
				int LF_b,LF_s;				
				
				//參數區 
				int BRangeDay;
				int SRangeDay;
				float Bratio;
				float Sratio;				
				
				int startLongIndex;
				int startShortIndex;
				int lastindex;
				float LongPrice;
				float ShortPrice;
				LongPrice=0;
				ShortPrice=0;
				
				if ([financialData count]>30) {
										
					
					LF_b=0;
					LF_s=0;
					LF_bout=0;
					LF_sout=0;	
					
										
					
					[aParaObject release];
					aParaObject=nil;
					aParaObject= [[ParaObject alloc] initWithTargetSymbol:symbol dwm:dwm] ;							
					
					NSMutableArray *para_lf;
					para_lf=[aParaObject CaArray_LF];					
					
					BRangeDay=[[[para_lf objectAtIndex:index_para] objectForKey:@"BRangeDay"] intValue];
					SRangeDay=[[[para_lf objectAtIndex:index_para] objectForKey:@"SRangeDay"] intValue];			
					Bratio=[[[para_lf objectAtIndex:index_para] objectForKey:@"Bratio"] floatValue];
					Sratio=[[[para_lf objectAtIndex:index_para] objectForKey:@"Sratio"] floatValue];					
					
					[aParaObject release];
					aParaObject=nil;
					
					NSString *action;
					
					for (int i=0; i<[financialData count]; i++) {					
						 
						
						if (i>0) {
							[csvDict release];
							csvDict=nil;				 
						}
						csvDict= [[NSMutableDictionary alloc] init];						
						
						//取出每日資料 
						{
							
							NSDictionary *fData = (NSDictionary *)[financialData objectAtIndex:i];		 
							close=[[fData objectForKey:@"close"] floatValue];		 
							//open=[[fData objectForKey:@"open"] floatValue];		 
							high=[[fData objectForKey:@"high"] floatValue];		 
							low=[[fData objectForKey:@"low"] floatValue];		 
							//volume=[[fData objectForKey:@"volume"] floatValue];	
							//adjclose=[[fData objectForKey:@"adjClose"] floatValue];						
							   
							
						}
						//取出前日資料 
						{
							if (i>=1) {
								NSDictionary *fData = (NSDictionary *)[financialData objectAtIndex:i-1];		 
								close_1=[[fData objectForKey:@"close"] floatValue];		 
								//open_1=[[fData objectForKey:@"open"] floatValue];		 
								//high_1=[[fData objectForKey:@"high"] floatValue];		 
								//low_1=[[fData objectForKey:@"low"] floatValue];		 
								//volume_1=[[fData objectForKey:@"volume"] floatValue];
								//adjclose_1=[[fData objectForKey:@"adjClose"] floatValue];		
								
								
							}
							
						}		
						
						//指標 移動均線 上=========== 
						float average1 ;
						//參數物件下的移動均線參數
						//averag1 主要計算給笑傲曲線使用
						average1=[self MovingAverage_record:csvDict index_i:i N_Indentfy:@"usedforLF" P_movingday:5 I_close:close];
						//設定前期資料使用
						if (i>=1) {
							average1_1=average1; //用於笑傲曲線 的第一根Ｋ線
						}									
						
						
						
						//買方之區間最高與最低差價
						float BRangeHigh,BRangeLow,BRange;
						{
							if (i>=BRangeDay) {
								BRangeHigh=high;
								for (int k=i;k>(i-BRangeDay) ; k--) {
									NSDictionary *fData = (NSDictionary *)[financialData objectAtIndex:k];		 
									if ([[fData objectForKey:@"high"] floatValue]>=BRangeHigh) {
										BRangeHigh=[[fData objectForKey:@"high"] floatValue];
									};			
								}			
								
							}
							else {
								BRangeHigh=high;
							}
							
							if (i>=BRangeDay) {
								BRangeLow=low;
								for (int k=i;k>(i-BRangeDay) ; k--) {
									NSDictionary *fData = (NSDictionary *)[financialData objectAtIndex:k];		 
									if ([[fData objectForKey:@"low"] floatValue]<=BRangeLow) {
										BRangeLow=[[fData objectForKey:@"low"] floatValue];
									};			
								}			
								
							}
							else {
								BRangeLow=low;
							}
							
						}
						BRange=BRangeHigh-BRangeLow; //Brange 表示買方策略區間的最高價與最低價之差
						
						//賣方之區間最高與最低差價
						float SRangeHigh,SRangeLow,SRange;
						{
							if (i>=SRangeDay) {
								SRangeHigh=high;
								for (int k=i;k>(i-SRangeDay) ; k--) {
									NSDictionary *fData = (NSDictionary *)[financialData objectAtIndex:k];		 
									if ([[fData objectForKey:@"high"] floatValue]>=SRangeHigh) {
										SRangeHigh=[[fData objectForKey:@"high"] floatValue];
									};			
								}			
								
							}
							if (i>=SRangeDay) {
								SRangeLow=low;
								for (int k=i;k>(i-SRangeDay) ; k--) {
									NSDictionary *fData = (NSDictionary *)[financialData objectAtIndex:k];		 
									if ([[fData objectForKey:@"low"] floatValue]<=SRangeLow) {
										SRangeLow=[[fData objectForKey:@"low"] floatValue];
									};			
								}			
								
							}
						}
						SRange=SRangeHigh-SRangeLow; //Srange 表示賣方策略區間的最高價與最低價之差		
						
						//開始計算笑傲曲線的重要數值
						action=@"0";						
						if (i>=10){
							//NSLog(@"fffff=%f close=%f" , LF_bout,close);
							if (LF_b==0 &&  LF_s==0 && close>average1 & close_1<average1_1 ) {
								LF_b=1; 
								LF_s=0;
								LF_bout=close-BRange*Bratio;
								LF_sout=0;
								startLongIndex=i;
								LongPrice=close;
								ShortPrice=0;
								action=@"1" ;
								
							}
							if ( LF_b==1 &  LF_bout+BRange<close) {
								LF_bout= LF_bout+BRange*Bratio;
							}
							if ( LF_b==1 && close< LF_bout) {
								LF_b=0;
								LF_s=1;
								LF_sout=close+SRange*Sratio;
								LF_bout=0;
								startShortIndex=i;
								LongPrice=0;
								ShortPrice=close;								
								action=@"-1";	
								
							}
							
							
							if ( LF_b==0 &&  LF_s==0 && close<average1 & close_1>average1_1 ) {
								LF_s=1;
								LF_b=0;
								LF_sout=close+SRange*Sratio;	
								LF_bout=0;
								startShortIndex=i;
								LongPrice=0;
								ShortPrice=close;	
								action=@"-1";									
								
							}		
							if ( LF_s==1 &  LF_sout-SRange>close) {
								LF_sout= LF_sout-SRange*Sratio;
							}	
							if ( LF_s==1 && close> LF_sout) {
								LF_s=0;
								LF_b=1;
								LF_bout=close-BRange*Bratio;
								LF_sout=0;
								startLongIndex=i;
								LongPrice=close;
								ShortPrice=0;	
								
								action=@"1" ;								
							}
							
							lastindex=i;
						} 		
						 		
						
						
					
					}
					
					NSString *outsignal;
					NSString *outBreakP;
					NSString *outLongDay;
					NSString *outShortDay;
					NSString *outLongProfit;
					NSString *outShortProfit;						
					
					if(LF_b==1){
						outsignal=NSLocalizedString( @"Long",@"多頭") ;
						outBreakP=[[NSString stringWithFormat:@"↓ %0.03f", LF_bout] copy];
						outLongDay=[[NSString stringWithFormat:@"%i",lastindex-startLongIndex+1] copy];
						outShortDay=@"0";
						if (LongPrice>0) {
							outLongProfit=[[NSString stringWithFormat:@"%0.02f",(close- LongPrice)/LongPrice*100] copy];
							
						}
						else {
							outLongProfit=[[NSString stringWithFormat:@"%i",0] copy];								
							
						}
						
						
						outShortProfit=@"0";
					}
					else {
						outsignal=NSLocalizedString( @"Short",@"空頭")  ;	
						outBreakP=[[NSString stringWithFormat:@"↑ %0.03f", LF_sout] copy];							
						outLongDay=@"0";
						outShortDay=[[NSString stringWithFormat:@"%i",lastindex-startShortIndex+1] copy];
						
						outLongProfit=@"0";
						if (ShortPrice>0) {
							
							outShortProfit=[[NSString stringWithFormat:@"%0.02f", (ShortPrice-close)/ShortPrice*100 ] copy];;							
							
						}
						else {
							
							outShortProfit=[[NSString stringWithFormat:@"%i", 0 ] copy];;							
						}
						
						
					}
					switch (index_para) {
						case 0:{
							LF_Signal1 = outsignal ;
							LF_BreakP1=outBreakP;
							LF_LongDay1=outLongDay;
							LF_ShortgDay1=outShortDay;
							LF_LongProfit1=outLongProfit;
							LF_ShortgProfit1=outShortProfit;
							LF_Action1=action;
							cLF_b1=[[NSString stringWithFormat:@"%i", LF_b] copy];
							cLF_s1=[[NSString stringWithFormat:@"%i", LF_s] copy];
							cLF_bout1=[[NSString stringWithFormat:@"%0.03f", LF_bout] copy];
							cLF_sout1=[[NSString stringWithFormat:@"%0.03f", LF_sout] copy];								
							
							break;
						}
						case 1:{
							LF_Signal2 =outsignal ;
							LF_BreakP2=outBreakP;
							LF_LongDay2=outLongDay;
							LF_ShortgDay2=outShortDay;	
							LF_LongProfit2=outLongProfit;
							LF_ShortgProfit2=outShortProfit;								
							LF_Action2=action;							
							cLF_b2=[[NSString stringWithFormat:@"%i", LF_b] copy];
							cLF_s2=[[NSString stringWithFormat:@"%i", LF_s] copy];
							cLF_bout2=[[NSString stringWithFormat:@"%0.03f", LF_bout] copy];
							cLF_sout2=[[NSString stringWithFormat:@"%0.03f", LF_sout] copy];								
							break;
						}								
						case 2:{
							LF_Signal3 =outsignal  ;
							LF_BreakP3=outBreakP;								
							LF_LongDay3=outLongDay;
							LF_ShortgDay3=outShortDay;	
							LF_LongProfit3=outLongProfit;
							LF_ShortgProfit3=outShortProfit;								
							LF_Action3=action;							
							
							cLF_b3=[[NSString stringWithFormat:@"%i", LF_b] copy];
							cLF_s3=[[NSString stringWithFormat:@"%i", LF_s] copy];
							cLF_bout3=[[NSString stringWithFormat:@"%0.03f", LF_bout] copy];
							cLF_sout3=[[NSString stringWithFormat:@"%0.03f", LF_sout] copy];								
							break;
						}								
						default:
							break;
					}					
					
				}			
				
				
			}		
			if ([[havetocalcuateTableIndicator objectAtIndex:i] hasPrefix: NSLocalizedString(@"MESA_FAMA", @"MESA_FAMA")] 
				|| [[havetocalcuateTableIndicator objectAtIndex:i] hasPrefix: NSLocalizedString(@"MESA_Action", @"MESA_動作")]				
				|| [[havetocalcuateTableIndicator objectAtIndex:i] hasPrefix: NSLocalizedString(@"MESA_Signal", @"MESA_訊號")]	
				|| [[havetocalcuateTableIndicator objectAtIndex:i] hasPrefix: NSLocalizedString(@"MESA_LongDay", @"MESA_買入天數")]	
				|| [[havetocalcuateTableIndicator objectAtIndex:i] hasPrefix: NSLocalizedString(@"MESA_ShortgProfit", @"MESA_賣出獲利率")]
				|| [[havetocalcuateTableIndicator objectAtIndex:i] hasPrefix: NSLocalizedString(@"MESA_LongProfit", @"MESA_買入獲利率")]	
				|| [[havetocalcuateTableIndicator objectAtIndex:i] hasPrefix: NSLocalizedString(@"MESA_ShortgDay", @"MESA_賣出天數")]				
				|| [[havetocalcuateTableIndicator objectAtIndex:i] hasPrefix: NSLocalizedString(@"MESA_MAMA", @"MESA_MAMA")]) {
				
				
				
				NSLog(@"Caluate_TableIndicator_MESA_FAMA_start");
				
				
				//NSMutableDictionary *csvDict ;
				
				int index_para;
				
				if ([[havetocalcuateTableIndicator objectAtIndex:i] isEqualToString: NSLocalizedString(@"MESA_FAMA1", @"MESA_FAMA1")]  ) {
				    index_para=0;
				}
				else if([[havetocalcuateTableIndicator objectAtIndex:i] isEqualToString: NSLocalizedString(@"MESA_FAMA2", @"MESA_FAMA2")]  ) {
					index_para=1;
				}
				else if([[havetocalcuateTableIndicator objectAtIndex:i] isEqualToString: NSLocalizedString(@"MESA_FAMA3", @"MESA_FAMA3")]  ) {
					index_para=2;
				}		
				else if ([[havetocalcuateTableIndicator objectAtIndex:i] isEqualToString: NSLocalizedString(@"MESA_MAMA1", @"MESA_MAMA1")]  ) {
				    index_para=0;
				}
				else if([[havetocalcuateTableIndicator objectAtIndex:i] isEqualToString: NSLocalizedString(@"MESA_MAMA2", @"MESA_MAMA2")]  ) {
					index_para=1;
				}
				else if([[havetocalcuateTableIndicator objectAtIndex:i] isEqualToString: NSLocalizedString(@"MESA_MAMA3", @"MESA_MAMA3")]  ) {
					index_para=2;
				}	
				else if ([[havetocalcuateTableIndicator objectAtIndex:i] isEqualToString: NSLocalizedString(@"MESA_Signal1", @"MESA_訊號1")]  ) {
				    index_para=0;
				}				
				else if ([[havetocalcuateTableIndicator objectAtIndex:i] isEqualToString: NSLocalizedString(@"MESA_Signal2", @"MESA_訊號2")]  ) {
				    index_para=1;
				}	
				else if ([[havetocalcuateTableIndicator objectAtIndex:i] isEqualToString: NSLocalizedString(@"MESA_Signal3", @"MESA_訊號3")]  ) {
				    index_para=2;
				}	
				else if ([[havetocalcuateTableIndicator objectAtIndex:i] isEqualToString: NSLocalizedString(@"MESA_Action1", @"MESA_動作1")]  ) {
				    index_para=0;
				}	
				else if ([[havetocalcuateTableIndicator objectAtIndex:i] isEqualToString: NSLocalizedString(@"MESA_Action2", @"MESA_動作2")]  ) {
				    index_para=1;
				}	
				else if ([[havetocalcuateTableIndicator objectAtIndex:i] isEqualToString: NSLocalizedString(@"MESA_Action3", @"MESA_動作3")]  ) {
				    index_para=2;
				}	
				else if([[havetocalcuateTableIndicator objectAtIndex:i] isEqualToString: NSLocalizedString(@"MESA_LongDay1", @"MESA_買入天數1")]  ) {
					index_para=0;
				}
				else if([[havetocalcuateTableIndicator objectAtIndex:i] isEqualToString: NSLocalizedString(@"MESA_LongDay2", @"MESA_買入天數2")]  ) {
					index_para=1;
				}				
				else if([[havetocalcuateTableIndicator objectAtIndex:i] isEqualToString: NSLocalizedString(@"MESA_LongDay3", @"MESA_買入天數3")]  ) {
					index_para=2;
				}				
				else if([[havetocalcuateTableIndicator objectAtIndex:i] isEqualToString: NSLocalizedString(@"MESA_ShortgDay1", @"MESA_賣出天數1")]  ) {
					index_para=0;
				}				
				else if([[havetocalcuateTableIndicator objectAtIndex:i] isEqualToString: NSLocalizedString(@"MESA_ShortgDay2", @"MESA_賣出天數2")]  ) {
					index_para=1;
				}
				else if([[havetocalcuateTableIndicator objectAtIndex:i] isEqualToString: NSLocalizedString(@"MESA_ShortgDay3", @"MESA_賣出天數3")]  ) {
					index_para=2;
				}				
				else if([[havetocalcuateTableIndicator objectAtIndex:i] isEqualToString: NSLocalizedString(@"MESA_LongProfit1", @"MESA_買入獲利率1")]  ) {
					index_para=0;
				}					
				else if([[havetocalcuateTableIndicator objectAtIndex:i] isEqualToString: NSLocalizedString(@"MESA_LongProfit2", @"MESA_買入獲利率2")]  ) {
					index_para=1;
				}				
				else if([[havetocalcuateTableIndicator objectAtIndex:i] isEqualToString: NSLocalizedString(@"MESA_LongProfit3", @"MESA_買入獲利率3")]  ) {
					index_para=2;
				}	
				else if([[havetocalcuateTableIndicator objectAtIndex:i] isEqualToString: NSLocalizedString(@"MESA_ShortgProfit1", @"MESA_賣出獲利率1")]  ) {
					index_para=0;
				}				
				else if([[havetocalcuateTableIndicator objectAtIndex:i] isEqualToString: NSLocalizedString(@"MESA_ShortgProfit2", @"MESA_賣出獲利率2")]  ) {
					index_para=1;
				}					
				else if([[havetocalcuateTableIndicator objectAtIndex:i] isEqualToString: NSLocalizedString(@"MESA_ShortgProfit3", @"MESA_賣出獲利率3")]  ) {
					index_para=2;
				}					
				else{
                    index_para=0;
                }
				
				//原始資料變數區
				float  high,low,close ;
				//float open_1,high_1,low_1,close_1,volume_1,adjclose_1;				
				
				 			
				
				//參數區 
				 			
				
				//int startLongIndex;
				//int startShortIndex;
				
				float LongPrice;
				float ShortPrice;
				LongPrice=0;
				ShortPrice=0;
				//多空方向
				int bs;
				bs=0;
				
				int startLongIndex=0;
				int startShortIndex=0;
				int lastindex=0;
				 			
				
				
				
				if ([financialData count]>30) {
				 	
					[aParaObject release];
					aParaObject=nil;
					aParaObject= [[ParaObject alloc] initWithTargetSymbol:symbol dwm:dwm] ;							
					
					NSMutableArray *para_lf=nil;
					para_lf=[aParaObject CaArray_MESA];					
					float FastLim;
					float SlowLim;					
					
					FastLim=[[[para_lf objectAtIndex:index_para] objectForKey:@"FastLim"] floatValue];
					SlowLim=[[[para_lf objectAtIndex:index_para] objectForKey:@"SlowLim"] floatValue];			
				 	
					[aParaObject release];
					aParaObject=nil;
					
					
					
					//MESA 通用變數區
					int array_account;
					array_account= [financialData count]+ 30;
					 
					float mama=0;
                    float fama=0;
					float Smooth[array_account];
					float price[array_account];
					float Detrender[array_account];
					float Period[array_account];
					float Q1[array_account];
					float l1[array_account];
					float jl[array_account];
					float jQ[array_account];
					float l2[array_account];
					float Q2[array_account];
					float Re[array_account];
					float lm[array_account];
					float SmoothPeriod[array_account];
					float Phase[array_account];
					float DeltaPhase[array_account];
					float alpha[array_account];
					float MAMA[array_account];
					float FAMA[array_account];						
					
					
					for (int i=0; i<[financialData count]+30; i++) {
						Smooth[i]=0;
						price[i]=0;
						Detrender[i]=0;
						Period[i]=0;
						Q1[i]=0;	 
						MAMA[i]=0;
						FAMA[i]=0;
					}						
					
					
					
					for (int i=0; i<[financialData count]; i++) {					
						
						/*
						if (i>0) {
							[csvDict release];
							csvDict=nil;				 
						}
						csvDict= [[NSMutableDictionary alloc] init];						
						*/
						//取出每日資料 
						{
							
							NSDictionary *fData = (NSDictionary *)[financialData objectAtIndex:i];		 
							close=[[fData objectForKey:@"close"] floatValue];		 
							//open=[[fData objectForKey:@"open"] floatValue];		 
							high=[[fData objectForKey:@"high"] floatValue];		 
							low=[[fData objectForKey:@"low"] floatValue];		 
							//volume=[[fData objectForKey:@"volume"] floatValue];	
							//adjclose=[[fData objectForKey:@"adjClose"] floatValue];						
							
							
						}
						//取出前日資料 
						{
							if (i>=1) {
								//NSDictionary *fData = (NSDictionary *)[financialData objectAtIndex:i-1];		 
								//close_1=[[fData objectForKey:@"close"] floatValue];		 
								//open_1=[[fData objectForKey:@"open"] floatValue];		 
								//high_1=[[fData objectForKey:@"high"] floatValue];		 
								//low_1=[[fData objectForKey:@"low"] floatValue];		 
								//volume_1=[[fData objectForKey:@"volume"] floatValue];
								//adjclose_1=[[fData objectForKey:@"adjClose"] floatValue];		
								
								
							}
							
						}		
						//計算MESA
						if (i>=10   ) {
							
							price[i]=(high +low)/2;		
							Smooth[i] =(4 * price[i] + 3 * price[i-1] + 2 * price[i-2] + price[i-3])/10;
							
							Detrender[i]=(0.0962*Smooth[i]+0.5769*Smooth[i-2]-0.5769*Smooth[i-4]-0.0962*Smooth[i-6])*(0.075*Period[i-1]+0.54);
							Q1[i]=(0.0962*Detrender[i]+0.5769*Detrender[i-2]-0.5769*Detrender[i-4]-0.0962*Detrender[i-6])*(0.075*Period[i-1]+0.54);
							
							l1[i]=Detrender[i-3];
							jl[i]=(0.0962*l1[i]+0.5769*l1[i-2]-0.5769*l1[i-4]-.0962*l1[i-6])*(0.075*Period[i-1]+0.54);	
							jQ[i]=(0.0962*Q1[i]+.5769*Q1[i-2]-.5769*Q1[i-4]-0.0962*Q1[i-6])*(0.075*Period[i-1]+0.54) ;
							l2[i]=l1[i]-jQ[i];
							Q2[i]=Q1[i]+jl[i];
							
							l2[i]=0.2*l2[i]+0.8*l2[i-1];
							Q2[i]=0.2*Q2[i]+0.8*Q2[i-1];
							Re[i]=l2[i]*l2[i-1]+Q2[i]*Q2[i-1];
							lm[i]=l2[i]*Q2[i-1]-Q2[i]*l2[i-1];
							Re[i]=0.2*Re[i]+0.8*Re[i-1];
							lm[i]=0.2*lm[i]+0.8*lm[i-1];
							
							
							if( lm[i] !=0 && Re[i] !=0 )
							{
								Period[i]= 360/(atan((lm[i]/Re[i]))*180/(4*atan(1)));
								
							}
							
							
							
							if( Period[i]>1.5*Period[i-1])
								Period[i]=1.5*Period[i-1];
							
							if(Period[i]<0.67*Period[i-1])
								Period[i]=0.67*Period[i-1];
							
							if(Period[i]<6)
								Period[i]=6;
							if(Period[i]>50)
								Period[i]=50;
							
							Period[i]=0.2*Period[i]+0.8*Period[i-1];
							
							// [csvDict setObject:[NSNumber numberWithFloat:Period[i]] forKey: @"Period"];	
							
							SmoothPeriod[i]=0.33*Period[i]+0.67*SmoothPeriod[i-1];
							
							if( l1[i] !=0 )
								Phase[i]=atan(Q1[i]/l1[i])*180/(4*atan(1));
							
							DeltaPhase[i]=Phase[i-1]-Phase[i];
							if(DeltaPhase[i]<1)
								DeltaPhase[i]=1;
							alpha[i]=FastLim/DeltaPhase[i];
							
							if(alpha[i]<SlowLim)
								alpha[i]=SlowLim;
							
							if( alpha[i]>FastLim)
								alpha[i]=FastLim;
							
							
							MAMA[i]=alpha[i]*price[i]+(1-alpha[i])*MAMA[i-1];
							FAMA[i]=0.5*alpha[i]*MAMA[i]+(1-0.5*alpha[i])*FAMA[i-1];			
							
							if ( FAMA[i]>MAMA[i] && FAMA[i-1]<MAMA[i-1]) {
								bs=-1;
								startShortIndex=i;
								LongPrice=0;
								ShortPrice=close;								
								
							}
							else if(FAMA[i]<MAMA[i] && FAMA[i-1]>MAMA[i-1]){
							    bs=1;
								startLongIndex=i;
								LongPrice=close;
								ShortPrice=0;								
								
								
							}
							else {
							    bs=0;
							}
							lastindex=i;
                            
                            mama=MAMA[i];
                            fama=FAMA[i];
							
						}
						else {
							mama=close;
                            fama=close;
							 						
							
						}						
						 
												
						//NSString *outsignal;
						//NSString *outBreakP;
						//NSString *outLongDay;
						//NSString *outShortDay;
						//NSString *outLongProfit;
						//NSString *outShortProfit;						
						
						
					}
					NSString *sFama ;
					NSString *sMama ;
					NSString *sbs;
					NSString *signals;
					
					NSString *outLongDay;
					NSString *outShortDay;
					NSString *outLongProfit;
					NSString *outShortProfit;					
					
					
					sFama=[[NSString stringWithFormat:@"%0.03f", fama] copy];
					sMama=[[NSString stringWithFormat:@"%0.03f", mama] copy];						
					sbs=[[NSString stringWithFormat:@"%i", bs] copy];	
					
					if (mama>fama) {
						signals=@"1";
						outLongDay=[[NSString stringWithFormat:@"%i",lastindex-startLongIndex+1] copy];
						outShortDay=@"0";	
						if (LongPrice>0) {
							outLongProfit=[[NSString stringWithFormat:@"%0.02f",(close- LongPrice)/LongPrice*100] copy];
							
						}
						else {
							outLongProfit=[[NSString stringWithFormat:@"%i",0] copy];								
							
						}
						
						
						outShortProfit=@"0";						
						
						
						
					}
					else {
						signals=@"-1";
						outLongDay=@"0";
						outShortDay=[[NSString stringWithFormat:@"%i",lastindex-startShortIndex+1] copy];
						
						outLongProfit=@"0";
						if (ShortPrice>0) {
							
							outShortProfit=[[NSString stringWithFormat:@"%0.02f", (ShortPrice-close)/ShortPrice*100 ] copy];;							
							
						}
						else {
							
							outShortProfit=[[NSString stringWithFormat:@"%i", 0 ] copy];;							
						}
						
					}

					
					switch (index_para) {
						case 0:{
							MESA_FAMA1 = sFama ;
							MESA_MAMA1=  sMama;
							MESA_bs1=sbs;
							MESA_Signal1=signals;
							
							MESA_LongDay1=outLongDay;
							MESA_ShortgDay1=outShortDay;
							MESA_LongProfit1=outLongProfit;
							MESA_ShortgProfit1=outShortProfit;							
							
							
							
							break;
						}
						case 1:{
							MESA_FAMA2 = sFama ;
							MESA_MAMA2=  sMama;
							MESA_bs2=sbs;
							MESA_Signal2=signals;	
							
							MESA_LongDay2=outLongDay;
							MESA_ShortgDay2=outShortDay;	
							
							MESA_LongProfit2=outLongProfit;
							MESA_ShortgProfit2=outShortProfit;								
							
							
							break;
						}								
						case 2:{
							MESA_FAMA3 = sFama ;
							MESA_MAMA3=  sMama;	
							MESA_bs3=sbs;
							MESA_Signal3=signals;	
							
							
							MESA_LongDay3=outLongDay;
							MESA_ShortgDay3=outShortDay;								
							
							MESA_LongProfit3=outLongProfit;
							MESA_ShortgProfit3=outShortProfit;								
							
							break;
						}								
						default:
							break;
					}
					
					
					//float Smooth[array_account];
					
					memset(Smooth, 0, sizeof(Smooth));					
					memset(price, 0, sizeof(price));					
					memset(Detrender, 0, sizeof(Detrender));		
					memset(Period, 0, sizeof(Period));					
					memset(Q1, 0, sizeof(Q1));					
					memset(l1, 0, sizeof(l1));
					
					memset(jl, 0, sizeof(jl));					
					memset(jQ, 0, sizeof(jQ));					
					memset(l2, 0, sizeof(l2));		
					memset(Q2, 0, sizeof(Q2));					
					memset(Re, 0, sizeof(Re));					
					memset(lm, 0, sizeof(lm));					
					
					memset(SmoothPeriod, 0, sizeof(SmoothPeriod));					
					memset(Phase, 0, sizeof(Phase));					
					memset(DeltaPhase, 0, sizeof(DeltaPhase));		
					memset(alpha, 0, sizeof(alpha));					
					memset(MAMA, 0, sizeof(MAMA));					
					memset(FAMA, 0, sizeof(FAMA));					
					/*
					 
					 
					 */
				}			
				NSLog(@"Caluate_TableIndicator_MESA_FAMA_end");				
			}		
			
		
		}		
         		
		
		
	}
	
	
	
	
	//最後計算結束
	[self.delgete afteCaluateTableIndicator];
}


#pragma mark -
#pragma mark 計算交易系統
 

-(void)Caluate_TradeSystem:(NSString *)funct{
	
    
	/*此函數的功能是要進行 funct的文字意義
	 @"S1":單一參數的計算 指定特定參數
	 @"M2":多參數的計算 但是指示顯式檢查用並不需要儲存 且記憶體不刪除
	 @"MM3":多參數的計算 是用來多股票的參數產生因此需要儲存記憶體 且刪除記憶體 (-(void)afterDownloadYahooDailyData)
	 */	
	
	//決定要使用哪一個程式交易策略
	NSString *Optimizetradesystem;	
	NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];	
    
	if ([prefs objectForKey:@"OptimizeTradeSystem"]==nil) {
		[prefs setObject:@"LF" forKey:@"OptimizeTradeSystem"];		
		[prefs synchronize];	
        Optimizetradesystem=@"LF";
        
	}
    
	else {
        Optimizetradesystem=[prefs objectForKey:@"OptimizeTradeSystem"]  ;
	}	
	
	
	NSLog(@"Caluate_TradeSystem (%@,%@,%@) ",Optimizetradesystem,symbol,id_class);		
	
	//最佳三個交易數 用來判斷是否要加入到資料庫或是刪除自選群組
	int count_0;
	int count_1;
	int count_2;
	 
	
	
	//停損出場率(%)	
    
    if ([prefs objectForKey:@"Optimizestopratearay"]==nil) {
		NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
		[prefs setObject:@"0.15" forKey:@"Optimizestopratearay"];
		[prefs synchronize];	 		
	}
    
	
	//買賣手續費率(%)
	if ([prefs objectForKey:@"Optimizescostfeeratearay"]==nil) {
		NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
		[prefs setObject:@"0.002" forKey:@"Optimizescostfeeratearay"];
		[prefs synchronize];	//將記憶體中的資料存到硬體上 儲存指令		
	}
    
	//買賣或是兩者都有的交易	
	if ([prefs objectForKey:@"buysellboth"]==nil) {
		NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
		[prefs setObject:@"僅作多" forKey:@"buysellboth"];
		[prefs synchronize];	 		
	}
    
	//進出場時間選擇	
	if ([prefs objectForKey:@"enterTime"]==nil) {
		NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
		[prefs setObject:@"當日" forKey:@"enterTime"];
		[prefs synchronize];	 		
	}
    
	//進出場價格選擇	
	if ([prefs objectForKey:@"enterprice"]==nil) {
		NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
		[prefs setObject:@"收盤價" forKey:@"enterprice"];
		[prefs synchronize];	 		
	}
    
	//進出場數量選擇	
	if ([prefs objectForKey:@"enternumber"]==nil) {
		NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
		[prefs setObject:@"單位:1" forKey:@"enternumber"];
		[prefs synchronize];	 		
	}
    
	
	
	
	
	//參數區
	 
	 
	
	NSAutoreleasePool *pool=[[NSAutoreleasePool alloc] init];	
	
	
	
    
    
	
	//原始資料變數區
	float open,high,low,close  ;
	float  close_1  ;
	
	//日期變數區
	NSDate *cdate;	
	NSDate *startdate;
	NSDate *enddate;
	
	//笑傲曲線通用變數
	float average1_1;	
	
	
	//MESA 通用變數區
	int array_account;
	array_account= [financialData count]+ 30;
	
	BOOL buysign[array_account];
	BOOL sellsign[array_account];
	
	
	float Smooth[array_account];
	float price[array_account];
	float Detrender[array_account];
	float Period[array_account];
	float Q1[array_account];
	float l1[array_account];
	float jl[array_account];
	float jQ[array_account];
	float l2[array_account];
	float Q2[array_account];
	float Re[array_account];
	float lm[array_account];
	float SmoothPeriod[array_account];
	float Phase[array_account];
	float DeltaPhase[array_account];
	float alpha[array_account];
	float MAMA[array_account];
	float FAMA[array_account];	
	//年度
	float year;	
	//buy 損益計算使用變數區
	int b_position;
	float b_totalcost,b_sumcostfee;
	float b_realizeGainLoss,b_unrealizeGainLoss,b_RUealizeGainLoss,b_PercentageRealizeGainLoss;
	float b_singleRealizeGL;
	int b_wincount,b_losscount;
	float b_PercentageunrealizeGainLoss;	
	float b_signreturn;
	//sell 損益計算使用變數區
	int s_position;
	float s_totalcost,s_sumcostfee;;
	float s_realizeGainLoss,s_unrealizeGainLoss,s_RUealizeGainLoss,s_PercentageRealizeGainLoss;
	float s_singleRealizeGL;	
	float s_wincount,s_losscount;
	float s_PercentageunrealizeGainLoss;
	float s_signreturn;	
	
	int bvol;
	int svol;
	float buyprice,sellprice;	
	float stopratio,costfeeratio; //停損率 交易費率
	NSString *Baction;
	NSString *Saction;	
	NSString *Bsign;
	NSString *Ssign;	
	
	//多參數表單紀錄物件實體
 	[financialData_TradeSystem_Optimize release];
	financialData_TradeSystem_Optimize=nil;
	financialData_TradeSystem_Optimize	=[[NSMutableArray alloc] init];	
	
	//循環參數物件
	NSMutableArray * paraobject;
	paraobject=[[NSMutableArray alloc] init];
	[paraobject autorelease];
	
	//1.針對不同策略要改的地方!!!!!!!
	//循環參數 的產生
	{
		//單一參數
		if ([funct isEqualToString:@"S1"]) {
            
			//表示僅需要單參數
			if ([Optimizetradesystem isEqualToString:@"MESA"]) {
				NSMutableArray *pMESA;
				pMESA=[aParaObject CaArray_MESA];				
                
                
				int pi;
				pi=[[prefs objectForKey:@"tradeindex"] intValue]-1; //參數順序					
				
				NSMutableDictionary *paras;
				paras=[[NSMutableDictionary alloc] init];
				[paras setObject:[NSString stringWithFormat:@"%0.03f",[[[pMESA objectAtIndex:pi] valueForKey:@"FastLim"] floatValue]]  forKey:@"FastLim"];
				[paras setObject:[NSString stringWithFormat:@"%0.03f",[[[pMESA objectAtIndex:pi] valueForKey:@"SlowLim"] floatValue]]   forKey:@"SlowLim"];
				[paraobject addObject:[paras mutableCopy]];
				[paras release];
				paras=nil;						
                
			}
			else if([Optimizetradesystem isEqualToString:@"LF"]) {
				NSMutableArray *pLF;
				pLF=[aParaObject CaArray_LF];				
				int pi;
				pi=[[prefs objectForKey:@"tradeindex"] intValue]-1; //參數順序					
				NSMutableDictionary *paras;
				paras=[[NSMutableDictionary alloc] init];
				
				[paras setObject:[NSString stringWithFormat:@"%i",[[[pLF objectAtIndex:pi] valueForKey:@"BRangeDay"] intValue]] forKey:@"BRangeDay"];
				[paras setObject:[NSString stringWithFormat:@"%i",[[[pLF objectAtIndex:pi] valueForKey:@"SRangeDay"] intValue]] forKey:@"SRangeDay"];
				[paras setObject:[NSString stringWithFormat:@"%0.03f",[[[pLF objectAtIndex:pi] valueForKey:@"Bratio"] floatValue]] forKey:@"Bratio"];
				[paras setObject:[NSString stringWithFormat:@"%0.03f",[[[pLF objectAtIndex:pi] valueForKey:@"Sratio"] floatValue]] forKey:@"Sratio"];				
				
				[paraobject addObject:[paras mutableCopy]];
				[paras release];
				paras=nil;					
				
			}					
			
			
			
		}
		//多參數
		else {
			//@"M2"   @"MM3"
			//表示需要產生多參數
			if ([Optimizetradesystem isEqualToString:@"MESA"]) {
				for (float FastLim=0.2; FastLim < 0.6; FastLim=FastLim+0.02) {
					for (float SlowLim=0.01; SlowLim< 0.3; SlowLim=SlowLim+0.02) {
						NSMutableDictionary *paras;
						paras=[[NSMutableDictionary alloc] init];
						[paras setObject:[NSString stringWithFormat:@"%0.03f",FastLim] forKey:@"FastLim"];
						[paras setObject:[NSString stringWithFormat:@"%0.03f",SlowLim] forKey:@"SlowLim"];
						
						[paraobject addObject:[paras mutableCopy]];
						[paras release];
						paras=nil;
					}	
				}		
			}
			else if([Optimizetradesystem isEqualToString:@"LF"]) {
				for (int BRangeDay=10; BRangeDay < 30; BRangeDay=BRangeDay+5) {
					for (int SRangeDay=10; SRangeDay< 30; SRangeDay=SRangeDay+5) {
						for (float Bratio=0.1; Bratio<0.3; Bratio=Bratio+0.05) {
							for (float Sratio=0.1; Sratio<0.3; Sratio=Sratio+0.05) {
								
								NSMutableDictionary *paras;
								paras=[[NSMutableDictionary alloc] init];
								[paras setObject:[NSString stringWithFormat:@"%i",BRangeDay] forKey:@"BRangeDay"];
								[paras setObject:[NSString stringWithFormat:@"%i",SRangeDay] forKey:@"SRangeDay"];
								[paras setObject:[NSString stringWithFormat:@"%0.03f",Bratio] forKey:@"Bratio"];
								[paras setObject:[NSString stringWithFormat:@"%0.03f",Sratio] forKey:@"Sratio"];				
								
								[paraobject addObject:[paras mutableCopy]];
								[paras release];
								paras=nil;								
								
							} 
							
                        }
                        
					}	
				}		
				
				
				
			}				
		}
    }
	//!!!!!!!!!!!!!!!!!!!!!!!!!!!!
	
	//LF
	//LFcaluateTemp *LFcalcuate;	
	
	
	NSString *writetofile;	
	
	float LF_bout,LF_sout;
	int LF_b,LF_s;
	if ( [financialData count]>180) {
		
		//參數進行測試
        NSLog(@"Symbol=%@ count=%i  ",symbol,[paraobject count] );
		
		for (int i=0 ; i<[paraobject count]; i++) {
			//NSLog(@"Symbol=%@ count=%i FastLim=%f  SlowLim=%f",symbol,[paraobject count],[[[paraobject objectAtIndex:i] objectForKey:@"FastLim"] floatValue],[[[paraobject objectAtIndex:i] objectForKey:@"SlowLim"] floatValue]);
	 		
			LF_b=0;
			LF_s=0;
			LF_bout=0;
			LF_sout=0;	
			
			float FastLim;
			float SlowLim;
			int BRangeDay;
			int SRangeDay;
			float Bratio;
			float Sratio;
			
			//2.針對不同策略要改的地方!!!!!!!		
			//取出循環參數
			if ([Optimizetradesystem isEqualToString:@"MESA"]) {
				
				
				FastLim=[[[paraobject objectAtIndex:i] objectForKey:@"FastLim"] floatValue];
				SlowLim=[[[paraobject objectAtIndex:i] objectForKey:@"SlowLim"] floatValue];
				
				
				
			}
			else if([Optimizetradesystem isEqualToString:@"LF"]) {
				// NSLog(@"Symbol=%@ count=%i BRangeDay=%i  SRangeDay=%i",symbol,[paraobject count],[[[paraobject objectAtIndex:i] objectForKey:@"BRangeDay"] intValue],[[[paraobject objectAtIndex:i] objectForKey:@"SRangeDay"] intValue]);
				
				
				BRangeDay=[[[paraobject objectAtIndex:i] objectForKey:@"BRangeDay"] intValue];
				SRangeDay=[[[paraobject objectAtIndex:i] objectForKey:@"SRangeDay"] intValue];			
				Bratio=[[[paraobject objectAtIndex:i] objectForKey:@"Bratio"] floatValue];
				Sratio=[[[paraobject objectAtIndex:i] objectForKey:@"Sratio"] floatValue];
				
			}
			//!!!!!!!!!!!!!!!!!!!!!!!!!
			
			//初始化技術指標紀錄內容 
			[financialData_TradeSystem release];
			financialData_TradeSystem=nil;
			financialData_TradeSystem	=[[NSMutableArray alloc] init];		
			
			for (int i=0; i<[financialData count]+30; i++) {
				buysign[i]=NO;
				sellsign[i]=NO;
				
			}	
			
			
			
			//3.針對不同策略要改的地方!!!!!!!		
			//通用變數初始化區
			if ([Optimizetradesystem isEqualToString:@"MESA"]) {
				//MESA 通用變數初始化區
				for (int i=0; i<[financialData count]+30; i++) {
					Smooth[i]=0;
					price[i]=0;
					Detrender[i]=0;
					Period[i]=0;
					Q1[i]=0;	 
					MAMA[i]=0;
					FAMA[i]=0;
                  
                    
				}				
			}
			else if([Optimizetradesystem isEqualToString:@"LF"]) {
				
				
			}
			//!!!!!!!!!!!!!!!!!!!!!!!!!		
			
			
			
			
			
			//損益計算初始化區
			b_PercentageunrealizeGainLoss=0; //未實現損益報酬率
			b_wincount=0 ;//贏次數
			b_losscount=0 ;//輸次數
			b_position=0;//部位
			b_totalcost=0;//成本
			b_realizeGainLoss=0; //已經實現損益
			 
			b_PercentageRealizeGainLoss=0; //已經實現損益報酬率加總	
			b_sumcostfee=0;		
			 	
			
			s_PercentageunrealizeGainLoss=0; //未實現損益報酬率
			s_wincount=0.0f;//贏次數
			s_losscount=0.0f;//輸次數
			s_position=0;//部位
			s_totalcost=0;//成本
			s_realizeGainLoss=0; //已經實現損益
		 
			s_PercentageRealizeGainLoss=0; //已經實現損益報酬率加總			
			s_sumcostfee=0;		
			 
			//計算後資料儲存單筆用
			
			
			
			NSMutableDictionary *csvDict ;			
			
			writetofile=@"";
			writetofile=[writetofile stringByAppendingFormat:@"id\tDate\tOpen\tClose\t"];
			
			if ([Optimizetradesystem isEqualToString:@"MESA"]){				
				writetofile=[writetofile stringByAppendingFormat:@"MAMA\tFAMA\t"];
			}
			else if([Optimizetradesystem isEqualToString:@"LF"]){
				writetofile=[writetofile stringByAppendingFormat:@"LF_b\tLF_bout\tLF_s\tLF_sout\t"];			
				
			}			
			
			writetofile=[writetofile stringByAppendingFormat:@"Bsign\tBaction\tSsign\tSaction\tbvol\tsvol\tb_position\ts_position\tb_totalcost\ts_totalcost\tb_sumcostfee\ts_sumcostfee\tb_realizeGainLoss\ts_realizeGainLoss\tb_singleRealizeGL\ts_singleRealizeGL\tb_wincount\tb_losscount\ts_wincount\ts_losscount\twinpercentage\tb_unrealizeGainLoss\ts_unrealizeGainLoss\tb_signreturn\tb_PercentageRealizeGainLoss\ts_signreturn\ts_PercentageRealizeGainLoss\tyear\tRETURN\t\n"];		
			
			//依日期順序進行每筆資料計算
			
			
			for (int i=0; i<[financialData count]; i++) {
				Baction=@"";
				Saction=@"";	
			 		
				b_singleRealizeGL=0;
				s_singleRealizeGL=0;
				b_signreturn=0;			
				s_signreturn=0;
				//NSLog(@"ffff=%0.03f",FastLim);			
				//初始化紀錄物件
				//只有記錄最後的一筆資料才是要留下來的資料
				if (i>0) {
					
					 
					csvDict=nil;				 
					
					
					
				}
				
				csvDict= [[[NSMutableDictionary alloc] init] autorelease];
				
				//取出每日資料 
				{
					
					NSDictionary *fData = (NSDictionary *)[financialData objectAtIndex:i];		 
					close=[[fData objectForKey:@"close"] floatValue];		 
					open=[[fData objectForKey:@"open"] floatValue];		 
					high=[[fData objectForKey:@"high"] floatValue];		 
					low=[[fData objectForKey:@"low"] floatValue];		 
				 					
					cdate= [fData objectForKey:@"date"];  
					
				}
				//取出前日資料 
				{
					if (i>=1) {
						NSDictionary *fData = (NSDictionary *)[financialData objectAtIndex:i-1];		 
						close_1=[[fData objectForKey:@"close"] floatValue];		 
						 		 
						 
						
					}
					
				}		
				//NSLog(@"iiii=%i close=%0.02f",i,close);
				
				
				if (i==0) {
					startdate=cdate;
					enddate=cdate;
				}
				else {
					enddate=cdate;
				}
				
				//指標 移動均線 上=========== 
				float average1 ;
				//參數物件下的移動均線參數
				//averag1 主要計算給笑傲曲線使用
				average1=[self MovingAverage_record:csvDict index_i:i N_Indentfy:@"usedforLF" P_movingday:5 I_close:close];
				//設定前期資料使用
				if (i>=1) {
					average1_1=average1; //用於笑傲曲線 的第一根Ｋ線
				}				
				
				
				//4.針對不同策略要改的地方!!!!!!!
				//計算主體
				//買賣訊
				
				BOOL buy_action;
				BOOL sell_action;
				BOOL b_stop_action;	
				BOOL s_stop_action;				
				buy_action=NO;
				sell_action=NO;
				b_stop_action=NO;
				s_stop_action=NO;
				
				{
					if ([Optimizetradesystem isEqualToString:@"MESA"]) {
						//MESA 計算主體
						if (i>=10   ) {
							
							price[i]=(high +low)/2;		
							Smooth[i] =(4 * price[i] + 3 * price[i-1] + 2 * price[i-2] + price[i-3])/10;
							
							Detrender[i]=(0.0962*Smooth[i]+0.5769*Smooth[i-2]-0.5769*Smooth[i-4]-0.0962*Smooth[i-6])*(0.075*Period[i-1]+0.54);
							Q1[i]=(0.0962*Detrender[i]+0.5769*Detrender[i-2]-0.5769*Detrender[i-4]-0.0962*Detrender[i-6])*(0.075*Period[i-1]+0.54);
							
							l1[i]=Detrender[i-3];
							jl[i]=(0.0962*l1[i]+0.5769*l1[i-2]-0.5769*l1[i-4]-.0962*l1[i-6])*(0.075*Period[i-1]+0.54);	
							jQ[i]=(0.0962*Q1[i]+.5769*Q1[i-2]-.5769*Q1[i-4]-0.0962*Q1[i-6])*(0.075*Period[i-1]+0.54) ;
							l2[i]=l1[i]-jQ[i];
							Q2[i]=Q1[i]+jl[i];
							
							l2[i]=0.2*l2[i]+0.8*l2[i-1];
							Q2[i]=0.2*Q2[i]+0.8*Q2[i-1];
							Re[i]=l2[i]*l2[i-1]+Q2[i]*Q2[i-1];
							lm[i]=l2[i]*Q2[i-1]-Q2[i]*l2[i-1];
							Re[i]=0.2*Re[i]+0.8*Re[i-1];
							lm[i]=0.2*lm[i]+0.8*lm[i-1];
							
							
							if( lm[i] !=0 && Re[i] !=0 )
							{
								Period[i]= 360/(atan((lm[i]/Re[i]))*180/(4*atan(1)));
								
							}
							
							
							
							if( Period[i]>1.5*Period[i-1])
								Period[i]=1.5*Period[i-1];
							
							if(Period[i]<0.67*Period[i-1])
								Period[i]=0.67*Period[i-1];
							
							if(Period[i]<6)
								Period[i]=6;
							if(Period[i]>50)
								Period[i]=50;
							
							Period[i]=0.2*Period[i]+0.8*Period[i-1];
							
							// [csvDict setObject:[NSNumber numberWithFloat:Period[i]] forKey: @"Period"];	
							
							SmoothPeriod[i]=0.33*Period[i]+0.67*SmoothPeriod[i-1];
							
							if( l1[i] !=0 )
								Phase[i]=atan(Q1[i]/l1[i])*180/(4*atan(1));
							
							DeltaPhase[i]=Phase[i-1]-Phase[i];
							if(DeltaPhase[i]<1)
								DeltaPhase[i]=1;
							alpha[i]=FastLim/DeltaPhase[i];
							
							if(alpha[i]<SlowLim)
								alpha[i]=SlowLim;
							
							if( alpha[i]>FastLim)
								alpha[i]=FastLim;
							
							
							MAMA[i]=alpha[i]*price[i]+(1-alpha[i])*MAMA[i-1];
							FAMA[i]=0.5*alpha[i]*MAMA[i]+(1-0.5*alpha[i])*FAMA[i-1];			
							
							
							[csvDict setObject:[NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%0.3f",MAMA[i]]] forKey:@"Tmama"];	
							[csvDict setObject:[NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%0.3f",FAMA[i]]] forKey:@"Tfama"];	
							
							
						}
						else {
							[csvDict setObject:[NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%i",0]] forKey:@"Tmama"];	
							[csvDict setObject:[NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%i",0]] forKey:@"Tfama"];
                            
                            MAMA[i]=close;
							FAMA[i]=close;
							
						}	
						
						 							
						
						
						//進出場訊號
						
						if ( MAMA[i] >  FAMA[i] && MAMA[i-1] <  FAMA[i-1]) {
							
							
							buysign[i]=YES;
						}
						if ( MAMA[i] <  FAMA[i] && MAMA[i-1] >  FAMA[i-1]) {
							
							sellsign[i]=YES;
						}						
						
						
					}
					else if([Optimizetradesystem isEqualToString:@"LF"]) {
						
						
						
						//買方之區間最高與最低差價
						float BRangeHigh,BRangeLow,BRange;
						{
							if (i>=BRangeDay) {
								BRangeHigh=high;
								for (int k=i;k>(i-BRangeDay) ; k--) {
									NSDictionary *fData = (NSDictionary *)[financialData objectAtIndex:k];		 
									if ([[fData objectForKey:@"high"] floatValue]>=BRangeHigh) {
										BRangeHigh=[[fData objectForKey:@"high"] floatValue];
									};			
								}			
								
							}
							else {
								BRangeHigh=high;
							}
							
							if (i>=BRangeDay) {
								BRangeLow=low;
								for (int k=i;k>(i-BRangeDay) ; k--) {
									NSDictionary *fData = (NSDictionary *)[financialData objectAtIndex:k];		 
									if ([[fData objectForKey:@"low"] floatValue]<=BRangeLow) {
										BRangeLow=[[fData objectForKey:@"low"] floatValue];
									};			
								}			
								
							}
							else {
								BRangeLow=low;
							}
							
						}
						BRange=BRangeHigh-BRangeLow; //Brange 表示買方策略區間的最高價與最低價之差
						
						//賣方之區間最高與最低差價
						float SRangeHigh,SRangeLow,SRange;
						{
							if (i>=SRangeDay) {
								SRangeHigh=high;
								for (int k=i;k>(i-SRangeDay) ; k--) {
									NSDictionary *fData = (NSDictionary *)[financialData objectAtIndex:k];		 
									if ([[fData objectForKey:@"high"] floatValue]>=SRangeHigh) {
										SRangeHigh=[[fData objectForKey:@"high"] floatValue];
									};			
								}			
								
							}
							if (i>=SRangeDay) {
								SRangeLow=low;
								for (int k=i;k>(i-SRangeDay) ; k--) {
									NSDictionary *fData = (NSDictionary *)[financialData objectAtIndex:k];		 
									if ([[fData objectForKey:@"low"] floatValue]<=SRangeLow) {
										SRangeLow=[[fData objectForKey:@"low"] floatValue];
									};			
								}			
								
							}
						}
						SRange=SRangeHigh-SRangeLow; //Srange 表示賣方策略區間的最高價與最低價之差		
						
						//開始計算笑傲曲線的重要數值
						if (i>=10){
							//NSLog(@"fffff=%f close=%f" , LF_bout,close);
							if (LF_b==0 &&  LF_s==0 && close>average1 & close_1<average1_1 ) {
								LF_b=1; 
								LF_s=0;
								LF_bout=close-BRange*Bratio;
								LF_sout=0;
								
							 	
								buysign[i]=YES;
								
							}
							if ( LF_b==1 &  LF_bout+BRange<close) {
								LF_bout= LF_bout+BRange*Bratio;
							}
							if ( LF_b==1 && close< LF_bout) {
								LF_b=0;
								LF_s=1;
								LF_sout=close+SRange*Sratio;
								LF_bout=0;
								
								sellsign[i]=YES;
								
							}
							
							
							if ( LF_b==0 &&  LF_s==0 && close<average1 & close_1>average1_1 ) {
								LF_s=1;
								LF_b=0;
								LF_sout=close+SRange*Sratio;	
								LF_bout=0;
								
								sellsign[i]=YES;
								
							}		
							if ( LF_s==1 &  LF_sout-SRange>close) {
								LF_sout= LF_sout-SRange*Sratio;
							}	
							if ( LF_s==1 && close> LF_sout) {
								LF_s=0;
								LF_b=1;
								LF_bout=close-BRange*Bratio;
								LF_sout=0;
								
								buysign[i]=YES;
								
							}
							
							
						} 		
						//紀錄檔
						{
							NSDecimalNumber *CBrangehigh = [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%0.2f",BRangeHigh]];		 
							[csvDict setObject:CBrangehigh forKey:@"CBrangehigh"];			
							NSDecimalNumber *CBrangelow = [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%0.2f",BRangeLow]];		 
							[csvDict setObject:CBrangelow forKey:@"CBrangelow"];			
							
							NSDecimalNumber *CSrangehigh = [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%0.2f",SRangeHigh]];		 
							[csvDict setObject:CSrangehigh forKey:@"CSrangehigh"];			
							NSDecimalNumber *CSrangelow = [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%0.2f",SRangeLow]];		 
							[csvDict setObject:CSrangelow forKey:@"CSrangelow"];			
							
							
							[csvDict setObject:[NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%i", LF_b]] forKey: @"LF_b" ];			
							[csvDict setObject:[NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%i", LF_s]] forKey: @"LF_s" ];			
							[csvDict setObject:[NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%0.3f", LF_bout]] forKey: @"LF_bout" ];			
							[csvDict setObject:[NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%0.3f", LF_sout]] forKey: @"LF_sout" ];			
							[csvDict setObject:[NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%0.2f",close]] forKey:@"close"];			
						}
						
						
						
						
					}	
				}
				//!!!!!!!!!!!!!!!!!!!!!!!!!!!!			
				if ( buysign[i]==YES ) {
					Bsign=@"Bsign";
				}
				else {
					Bsign=@"";
				}
				if ( sellsign[i]==YES ) {
					Ssign=@"Ssign";
				}
				else {
					Ssign=@"";
				}			
				
				//5針對不同策略要改的地方!!!!!!!		
				//訊號與進出點
				/*
				 if ([Optimizetradesystem isEqualToString:@"MESA"]) {
				 
				 
				 
				 
				 }
				 else if([Optimizetradesystem isEqualToString:@"LF"]) {
				 
				 
				 
				 
				 
				 
				 
				 }
				 */
				
				//停損率
				stopratio=[[prefs objectForKey:@"Optimizestopratearay"] floatValue]*-1 ;
				//手續費率
				costfeeratio=[[prefs objectForKey:@"Optimizescostfeeratearay"] floatValue];
				
				
				
				int lagday;			
				
				lagday=0;  //當日
				
				if ([[prefs objectForKey:@"enterTime"] isEqualToString:@"當日" ] ) {
					lagday=0;
					
				}
				else if([[prefs objectForKey:@"enterTime"] isEqualToString:@"後一日" ]){
					lagday=-1; //後一日
					
				}
				else if([[prefs objectForKey:@"enterTime"] isEqualToString:@"後二日" ]){
					lagday=-2; //後一日				
					
				}			
				//進出場時點 買賣訊隔日收盤價
				if ( buysign[i+lagday]==YES  ) {
					//買進訊號
					buy_action=YES;
					
				} 
				else if ( sellsign[i+lagday]==YES  ) {
					//賣出訊號
					sell_action=YES;
					
				}	
				else if(b_PercentageunrealizeGainLoss<stopratio  ){  
					//停損賣出訊號
					b_stop_action=YES;
					
					
				}						
				else if(s_PercentageunrealizeGainLoss<stopratio  ){   
					//停損賣出訊號
					s_stop_action=YES;
					
					
				}					
				
				//!!!!!!!!!!!!!!!!!!!!!!!!!			
				
				//開始處理進出場訊號 算出損益與勝率 上
				{
					
					//記錄進出場訊號			
					if ( buysign[i]==YES) {
						
						[csvDict setObject: @"B"  forKey:@"BSsignal"];
					}
					if ( sellsign[i]==YES) {
						
						[csvDict setObject: @"S"  forKey:@"BSsignal"];	
					}	
					
					//buy 計算每日未實現損益			
					b_unrealizeGainLoss=(b_position*close-b_totalcost);				
					if (b_totalcost>0) {
						//b_PercentageunrealizeGainLoss=(b_position*close-b_totalcost)/b_totalcost;
					} 
					else {
						//b_PercentageunrealizeGainLoss=0;
					}
					//sell 計算每日未實現損益			
					s_unrealizeGainLoss=(s_position*close-s_totalcost);				
					if (s_totalcost<0) {
						//s_PercentageunrealizeGainLoss=(s_position*close-s_totalcost)/s_totalcost;
					} 
					else {
						//s_PercentageunrealizeGainLoss=0;
					}				
					
					
					
					//進出場價格選擇
					
					if ([[prefs objectForKey:@"enterprice"] isEqualToString:@"開盤價" ] ) {
						//NSLog(@"開盤價");
						buyprice=open;
						sellprice=open;					
						
					}				
					else if ([[prefs objectForKey:@"enterprice"] isEqualToString:@"收盤價" ] ){
						//NSLog(@"收盤價");
						buyprice=close;
						sellprice=close;						
						
					}
					else if ([[prefs objectForKey:@"enterprice"] isEqualToString:@"最高價" ] ){
						NSLog(@"最高價");
						buyprice=high;
						sellprice=high;						
						
						
					}	
					else if ([[prefs objectForKey:@"enterprice"] isEqualToString:@"最低價" ] ){
						buyprice=low;
						sellprice=low;	
						
					}					
					
					
					bvol=0;
					svol=0;
					//buy
					if ([[prefs objectForKey:@"buysellboth"] isEqualToString:@"僅作多"] ||[[prefs objectForKey:@"buysellboth"] isEqualToString:@"多空雙向"]) {
						//buy 執行動作
						if (buy_action==YES) {
							//買進訊號
							Baction=@"BE";
							[csvDict setObject: @"BE"  forKey:@"BSsignalNextDay"];	
							[csvDict setObject: [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%0.3f",buyprice]]  forKey:@"B_price"];				
							
							if ([[prefs objectForKey:@"enternumber"] isEqualToString:@"單位:1" ] ) {
								bvol=1;
							}
							else if([[prefs objectForKey:@"enternumber"] isEqualToString:@"金額:5萬" ]){
								bvol=(50000/buyprice);						
							}
							else if([[prefs objectForKey:@"enternumber"] isEqualToString:@"金額:1百萬" ]){
								bvol=(1000000/buyprice);						
								
							}					
							else {
								bvol=999;
							}
							
							
							
							
							b_position=b_position+bvol ;
							b_totalcost=b_totalcost+bvol*buyprice+bvol*buyprice*costfeeratio;
							b_sumcostfee=b_sumcostfee+bvol*buyprice*costfeeratio;
							
							
							
						} 
						else if (sell_action==YES) {
							//賣出訊號
							
							Baction=@"BX";
							[csvDict setObject: @"BX"  forKey:@"BSsignalNextDay"];	
							[csvDict setObject: [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%0.3f",sellprice]]  forKey:@"S_price"];				
							
							if (b_position>0) {
								//計算以實現損益
								
								
								if (b_totalcost>0) {
									b_signreturn=(b_position*sellprice-b_totalcost-b_position*sellprice*costfeeratio)/b_totalcost*100;							
									b_PercentageRealizeGainLoss=b_PercentageRealizeGainLoss+b_signreturn;
									
								}
								
								
								b_singleRealizeGL=(b_position*sellprice-b_totalcost-b_position*sellprice*costfeeratio);
								b_realizeGainLoss=b_realizeGainLoss+b_singleRealizeGL;						
								
								b_sumcostfee=b_sumcostfee+b_position*sellprice*costfeeratio;
								
								b_position=0;
								b_totalcost=0;
								b_unrealizeGainLoss=0;
								
								if (b_singleRealizeGL>0) {
									b_wincount=b_wincount+1;
								}
								else {
									b_losscount=b_losscount+1;
								}						
								
								
							}
							
							
						}	
						else if(b_stop_action==YES){
							//停損賣出訊號
							Baction=@"BS";
							[csvDict setObject: @"BS"  forKey:@"BSsignalNextDay"];	
							[csvDict setObject: [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%0.3f",sellprice]]  forKey:@"S_price"];				
							if (b_position>0) {
								//計算以實現損益
								
								if (b_totalcost>0) {
									b_signreturn=(b_position*sellprice-b_totalcost-b_position*sellprice*costfeeratio)/b_totalcost*100;							
									b_PercentageRealizeGainLoss=b_PercentageRealizeGainLoss+b_signreturn;
									
								}
								
								b_singleRealizeGL=(b_position*sellprice-b_totalcost-b_position*sellprice*costfeeratio);						
								b_realizeGainLoss=b_realizeGainLoss+b_singleRealizeGL;
								b_sumcostfee=b_sumcostfee+b_position*sellprice*costfeeratio;
								b_position=0;
								b_totalcost=0;
								b_unrealizeGainLoss=0;
								
								if (b_singleRealizeGL>0) {
									
									b_wincount=b_wincount+1;
								}
								else {
									
									b_losscount=b_losscount+1;
								}									
								
								
							}					 
							
							
							
						}
						
						
						
					}
					
					//sell
					if ([[prefs objectForKey:@"buysellboth"] isEqualToString:@"僅作空"] ||[[prefs objectForKey:@"buysellboth"] isEqualToString:@"多空雙向"]) {
						
						//sell 執行動作
						if (sell_action==YES) {
							
							//賣出訊號					
							
							Saction=@"SE";
							[csvDict setObject: @"SE"  forKey:@"BSsignalNextDay"];	
							[csvDict setObject: [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%0.3f",sellprice]]  forKey:@"S_price"];				
							
							
							
							
							if ([[prefs objectForKey:@"enternumber"] isEqualToString:@"單位:1" ] ) {
								svol=-1;
							}
							else if([[prefs objectForKey:@"enternumber"] isEqualToString:@"金額:5萬" ]){
								svol=-1*(50000/sellprice);						
							}
							else if([[prefs objectForKey:@"enternumber"] isEqualToString:@"金額:1百萬" ]){
								svol=-1*(1000000/sellprice);					
								
							}					
							else {
								svol=999;
							}					
							
							
							
							
							s_position=s_position+svol ;
							s_totalcost=s_totalcost+svol*sellprice+(svol*sellprice*costfeeratio*-1); 
							s_sumcostfee=s_sumcostfee+(svol*sellprice*costfeeratio*-1);
							
							
							
							
						} 
						else if (buy_action==YES) {
							//買進訊號
							
							Saction=@"SX";
							[csvDict setObject: @"SX"  forKey:@"BSsignalNextDay"];	
							[csvDict setObject: [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%0.3f",buyprice]]  forKey:@"B_price"];				
							
							if (s_position<0) {
								//計算以實現損益
								
								
								if (s_totalcost<0) {
									s_signreturn=(s_position*buyprice-s_totalcost-s_position*buyprice*costfeeratio*-1)/s_totalcost*100*-1;							
									s_PercentageRealizeGainLoss=s_PercentageRealizeGainLoss+s_signreturn;
									
								}
								
								s_singleRealizeGL=(s_position*buyprice-s_totalcost-s_position*buyprice*costfeeratio*-1);
								s_realizeGainLoss=s_realizeGainLoss+s_singleRealizeGL;
								s_sumcostfee=s_sumcostfee+s_position*buyprice*costfeeratio*-1;
								s_position=0;
								s_totalcost=0;
								s_unrealizeGainLoss=0;
								
								if (s_singleRealizeGL >0) {
									s_wincount=s_wincount+1;
								}
								else {
									s_losscount=s_losscount+1;
								}							
								
								
								
							}
							
							
						}	
						else if(s_stop_action==YES){
							//停損賣出訊號
							
							Saction=@"SS";
							
							[csvDict setObject: @"SS"  forKey:@"BSsignalNextDay"];	
							[csvDict setObject: [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%0.3f",buyprice]]  forKey:@"B_price"];				
							if (s_position<0) {
								//計算以實現損益
								
								if (s_totalcost<0) {
									
									s_signreturn=(s_position*buyprice-s_totalcost-s_position*buyprice*costfeeratio*-1)/s_totalcost*100*-1;							
									
									s_PercentageRealizeGainLoss=s_PercentageRealizeGainLoss+s_signreturn;
									
								}
								
								s_singleRealizeGL=(s_position*sellprice-s_totalcost-s_position*buyprice*costfeeratio*-1);
								s_realizeGainLoss=s_realizeGainLoss+s_singleRealizeGL;
								s_sumcostfee=s_sumcostfee+s_position*buyprice*costfeeratio*-1;						
								
								s_position=0;
								s_totalcost=0;
								s_unrealizeGainLoss=0;
								
								if (s_singleRealizeGL>0) {
									s_wincount=s_wincount+1;
								}
								else {
									s_losscount=s_losscount+1;
								}							
								
								
								
								
							}					 
							
							
							
						}				
						
						
						
					}				
					
					
					
					//以實現損益＋未實現損益
					b_RUealizeGainLoss=b_realizeGainLoss+b_unrealizeGainLoss;		
					s_RUealizeGainLoss=s_realizeGainLoss+s_unrealizeGainLoss;		
					
					
					NSTimeInterval  l;
					l=[enddate timeIntervalSinceDate:startdate]/86400;
					
					year=l/365;		
					
					//buy計算每日未實現損益			
					b_unrealizeGainLoss=(b_position*close-b_totalcost);				
					if (b_totalcost>0) {
						b_PercentageunrealizeGainLoss=(b_position*close-b_totalcost)/b_totalcost;				
					} 
					else {
						b_PercentageunrealizeGainLoss=0;					
					}				
					
					//sell計算每日未實現損益			
					s_unrealizeGainLoss=(s_position*close-s_totalcost);				
					if (s_totalcost>0) {
						s_PercentageunrealizeGainLoss=(s_position*close-s_totalcost)/s_totalcost;				
					} 
					else {
						s_PercentageunrealizeGainLoss=0;					
					}						
					
					
					
					//記入今日買賣結果與損益結果
					//startdate
					[csvDict setObject: startdate  forKey:@"startdate"];				
					//enddate
					[csvDict setObject: enddate  forKey:@"enddate"];				
					
					//記錄週期
					[csvDict setObject: dwm  forKey:@"dwm"];				
					
					//紀錄日期用
					[csvDict setObject:cdate forKey:@"Tdate"];
					[csvDict setObject:[NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%0.3f",close]] forKey:@"Tclose"];						
					
					//記錄使用參數
					if ([Optimizetradesystem isEqualToString:@"MESA"]){
						
						//FastLim
						[csvDict setObject: [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%0.3f",FastLim]]  forKey:@"FastLim"];				
						//SlowLim
						[csvDict setObject: [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%0.3f",SlowLim]]  forKey:@"SlowLim"];				
						
						
					}				
					else if([Optimizetradesystem isEqualToString:@"LF"]){
						
						
						//BRangeDay
						[csvDict setObject: [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%i",BRangeDay]]  forKey:@"BRangeDay"];				
						//SRangeDay
						[csvDict setObject: [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%i",SRangeDay]]  forKey:@"SRangeDay"];				
						//Bratio
						[csvDict setObject: [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%0.3f",Bratio]]  forKey:@"Bratio"];				
						//Sratio
						[csvDict setObject: [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%0.3f",Sratio]]  forKey:@"Sratio"];				
						
						
					}				
					
					
					
					//close
					[csvDict setObject: [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%0.3f",close]]  forKey:@"close"];				
					
					//部位
					[csvDict setObject: [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%i",b_position+s_position]]  forKey:@"Position"];				
					//買入成本
					[csvDict setObject: [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%0.3f",b_totalcost+s_totalcost]]  forKey:@"Totalcost"];				
					
					//浮動損益
					[csvDict setObject: [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%0.3f",b_unrealizeGainLoss+s_unrealizeGainLoss]]  forKey:@"unrealizeGainLoss"];				
					
					//已經實現損益 buy+sell
					[csvDict setObject: [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%0.3f",b_realizeGainLoss+s_realizeGainLoss]]  forKey:@"RealizeGainLoss"];	
					//已經實現損益 buy 
					[csvDict setObject: [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%0.3f",b_realizeGainLoss ]]  forKey:@"b_RealizeGainLoss"];	
					//已經實現損益 sell 
					[csvDict setObject: [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%0.3f",s_realizeGainLoss ]]  forKey:@"s_RealizeGainLoss"];					
					
					
					//已實現損益＋未實現損益
					[csvDict setObject: [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%0.3f",b_RUealizeGainLoss+s_RUealizeGainLoss]]  forKey:@"RUealizeGainLoss"];				
					//總報酬率
					[csvDict setObject: [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%0.3f",b_PercentageRealizeGainLoss+s_PercentageRealizeGainLoss]]  forKey:@"PercentageRealizeGainLoss"];				
					
					//年報酬率
					if (year>0) {
						
						[csvDict setObject: [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%0.3f",(b_PercentageRealizeGainLoss+s_PercentageRealizeGainLoss)/year]]  forKey:@"YearPercentageRealizeGainLoss"];				
						[csvDict setObject: [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%0.3f",b_PercentageRealizeGainLoss/year]]  forKey:@"b_YearPercentageRealizeGainLoss"];				
						[csvDict setObject: [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%0.3f",s_PercentageRealizeGainLoss/year]]  forKey:@"s_YearPercentageRealizeGainLoss"];				
						
						
					}
					else {
						
						
						[csvDict setObject: [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%i",0]]  forKey:@"YearPercentageRealizeGainLoss"];				
						[csvDict setObject: [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%i",0]]  forKey:@"b_YearPercentageRealizeGainLoss"];				
						[csvDict setObject: [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%i",0]]  forKey:@"s_YearPercentageRealizeGainLoss"];					
						
					}
					
					
					
					//贏交易次數
					[csvDict setObject: [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%f", s_wincount+s_wincount]]  forKey:@"Wincount"];
					//輸交易次數
					[csvDict setObject: [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%f",b_losscount+s_losscount]]  forKey:@"Losscount"];
					//總交易次數
					int totalcounts;
					totalcounts=b_wincount + b_losscount +s_wincount+s_losscount;
					int b_totalcounts;
					b_totalcounts=b_wincount + b_losscount  ;				
					int s_totalcounts;
					s_totalcounts=s_wincount + s_losscount  ;						
					[csvDict setObject: [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%i",totalcounts]]  forKey:@"TotalCount"];		
					[csvDict setObject: [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%i",b_totalcounts]]  forKey:@"b_TotalCount"];		
					[csvDict setObject: [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%i",s_totalcounts]]  forKey:@"s_TotalCount"];		
					
					
					//勝率 buy+sell
					if ((b_wincount + b_losscount +s_wincount+s_losscount)>0) {
						
						[csvDict setObject: [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%0.003f",(b_wincount+s_wincount ) /(b_wincount + b_losscount +s_wincount+s_losscount)*100]]  forKey:@"WinPercentage"];				 
						
						
					}
					else {
						[csvDict setObject: [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%i",0]]  forKey:@"WinPercentage"];			 
						
					}
					//勝率 buy				
					if ((b_wincount + b_losscount  )>0) {
						
						[csvDict setObject: [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%i", b_wincount  /(b_wincount + b_losscount )*100]]  forKey:@"b_WinPercentage"];				 
						
						
					}
					else {
						[csvDict setObject: [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%i",0]]  forKey:@"b_WinPercentage"];			 
						
					}
					
					//勝率 sell				
					if ((s_wincount + s_losscount)>0.0f) {
						// NSLog(@">0 =%i =%i", s_wincount,s_losscount);					
						[csvDict setObject: [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%0.003f", s_wincount  /(s_wincount + s_losscount )*100]]  forKey:@"s_WinPercentage"];				 
						
						
					}
					else {
						// NSLog(@"=0 =%i =%i", s_wincount,s_losscount);	
						
						[csvDict setObject: [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%0.003f",0.0f]]  forKey:@"s_WinPercentage"];			 
						
					}				
					
					if ([funct isEqualToString:@"S1"]){
						[financialData_TradeSystem addObject: csvDict  ];
                        //[csvDict release];
					}
					
					
					
				}
				
				
				
				//開始處理進出場訊號 算出損益與勝率 下
				
				//是否將計算出來的數據寫入txt檔當作驗算用
				if ([prefs boolForKey:@"isWriteToTXT"]==YES) {
					
					//順序
					writetofile=[writetofile stringByAppendingFormat:@"id=%i\t",i];
					//日期
					NSDateFormatter * starta = [[NSDateFormatter alloc]init];
					[starta setDateFormat:@"yyyy/MM/dd"];
					NSString *wstart = [starta stringFromDate:cdate];
                    [starta release];
                    
					writetofile= [writetofile stringByAppendingFormat:@"%@\t",wstart];
					//開盤價收盤價
					writetofile=[writetofile stringByAppendingFormat:@"%0.03f\t%0.03f\t",open,close];
					if ([Optimizetradesystem isEqualToString:@"MESA"]){				
						writetofile=[writetofile stringByAppendingFormat:@"%0.03f\t%0.03f\t",MAMA[i],FAMA[i]];
					}
					else if([Optimizetradesystem isEqualToString:@"LF"]){
						writetofile=[writetofile stringByAppendingFormat:@"%i\t%0.03f\t%i\t%0.03f\t", LF_b, LF_bout, LF_s, LF_sout];
						
					}	
					float winp;
					if( (b_wincount + b_losscount + s_wincount+s_losscount) > 0 ){
						
						winp=(b_wincount+s_wincount)/(b_wincount + b_losscount +s_wincount+s_losscount)*100;
						
					}
					else {
						
						winp=0;
					}
					writetofile=[writetofile stringByAppendingFormat:@"%@\t%@\t%@\t%@\t%i\t%i\t\%i\t%i\t%0.03f\t%0.03f\t%0.03f\t%0.03f\t%0.03f\t%0.03f\t%0.03f\t%0.03f\t%i\t%i\t%0.1f\t%0.1f\t%0.03f\t%0.03f\t%0.03f\t%0.03f\t%0.03f\t%0.03f\t%0.03f\t%0.03f\t%0.03f\t\n",Bsign,Baction,Ssign,Saction,bvol,svol,b_position,s_position,b_totalcost,s_totalcost,b_sumcostfee,s_sumcostfee,b_realizeGainLoss,s_realizeGainLoss,b_singleRealizeGL,s_singleRealizeGL,b_wincount,b_losscount,s_wincount,s_losscount,winp,b_unrealizeGainLoss,s_unrealizeGainLoss,b_signreturn,b_PercentageRealizeGainLoss,s_signreturn,s_PercentageRealizeGainLoss,year,(b_PercentageRealizeGainLoss+s_PercentageRealizeGainLoss)/year];
					
					
					
					
					
				} 
				
				
				
			}
			//將每個參數所算出來的最後一筆資料儲存
			[financialData_TradeSystem_Optimize addObject: csvDict  ];
            //[csvDict release];
            
			//是否將計算出來的數據寫入txt檔當作驗算用
			
			if ([Optimizetradesystem isEqualToString:@"MESA"]) {		
				
				// NSLog(@"MESA S=%@ c=%i i=%i  ",symbol,[paraobject count],i);
			}
			
			else {
				
				
				//勝率
				if ((b_wincount + b_losscount +s_wincount+s_losscount)>0) {
					
					//	NSLog(@"LF S=%@ c=%i i=%i BD=%i SD=%i Br=%0.03f Sr=%0.03f win=%0.03f ",symbol,[paraobject count],i,BRangeDay,SRangeDay,Bratio,Sratio,(b_wincount+s_wincount ) /(b_wincount + b_losscount +s_wincount+s_losscount)*100);		 
				}
				else {
					
					
				 	//	NSLog(@"LF S=%@ c=%i i=%i BD=%i SD=%i Br=%0.03f Sr=%0.03f win=%0.03f ",symbol,[paraobject count],i,BRangeDay,SRangeDay,Bratio,Sratio,0);	
				}
				
				
				
				
				
				
			}
			
			
			
			
			
			if ([prefs boolForKey:@"isWriteToTXT"]==YES) {
				//將資料存在txt
				NSArray *arrayPaths = 
				NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES);
				NSString *docDir = [arrayPaths objectAtIndex:0];				
				NSString *newFilePath;				
				if ([Optimizetradesystem isEqualToString:@"MESA"]){				
					newFilePath= [docDir stringByAppendingFormat:@"/%@_%@_%0.03f_%0.03f.txt",symbol,Optimizetradesystem,FastLim,SlowLim];
				}
				else if([Optimizetradesystem isEqualToString:@"LF"]){
					newFilePath= [docDir stringByAppendingFormat:@"/%@_%@_%i_%i_%0.03f_%0.03f.txt",symbol,Optimizetradesystem,BRangeDay,SRangeDay,Bratio,Sratio];			
					
				}
				
				[writetofile writeToFile:newFilePath atomically:YES encoding:NSUTF8StringEncoding error:nil];				
			 	
				
				
				
			}
			
			
			
			
		}
		
		//[paraobject release];
		
		//多參數處理
		if ([funct isEqualToString:@"M2"] || [funct isEqualToString:@"MM3"]) {
			//1.進入多參數排序比較階段
			/*
             每檔股票參數的選取理論：因為有些股票的走勢只有走ㄧ大波,也許兩年才有依次大行情,
			 如果是以報酬率為先選擇標準,這樣會有偏誤,所以第一個是以勝率為準,這樣的話
			 系統比較穩定與客觀,之後則再以報酬率,交易次數為篩選標準,最後交易次數應該是
			 以越多交易次數越多越佳,主要還是避免幾次的大賺,雖然可能造成交易次數過多
             產業群組內,挑選哪檔股票當作程式交易的標準:以報酬率為優先考慮,主要是因為在參數篩選過程中
             已經先考慮到單次獲利太高的問題,且當然要選報酬率越高的股票當作標準 
			 
			 
             */
			//依照勝率排序
			NSArray *sortWinPercentage = [financialData_TradeSystem_Optimize sortedArrayUsingFunction:comparator_WinPercentage context:nil];	
			//取出勝率前20名的 
			NSMutableArray *sortWinPercentage10;
			sortWinPercentage10=[[NSMutableArray alloc] init];
			for (int k=0 ; k<=20 ; k++) {
				[sortWinPercentage10 addObject: [sortWinPercentage objectAtIndex:k ]  ];
			}
			//依照年報酬慮排序
			NSArray *sortYearPercentageRealizeGainLoss=[sortWinPercentage10 sortedArrayUsingFunction:comparator_YearPercentageRealizeGainLoss context:nil];
			//取出年報酬慮前12名
			NSMutableArray *sortYearPercentageRealizeGainLoss5;	
			sortYearPercentageRealizeGainLoss5=[[NSMutableArray alloc] init];
			for (int k0=0 ; k0<=11 ; k0++) {
				[sortYearPercentageRealizeGainLoss5 addObject: [sortYearPercentageRealizeGainLoss objectAtIndex:k0 ]  ];
			}	
			
			//依照交易次數排序
			NSArray *sortTotalCount=[sortYearPercentageRealizeGainLoss5 sortedArrayUsingFunction:comparator_TotalCount context:nil];
			financialData_TradeSystem_Optimize= [sortTotalCount mutableCopy];
			
			//2.最佳化結果寫入資料庫內========== 	
			//次數最多策略
			
 			NSDictionary *toData0=[financialData_TradeSystem_Optimize objectAtIndex:0];
			NSDictionary *toData1=[financialData_TradeSystem_Optimize objectAtIndex:5];	
			NSDictionary *toData2=[financialData_TradeSystem_Optimize objectAtIndex:11];		
            
			count_0=[[toData0 objectForKey:@"TotalCount"] intValue ];		
			count_1=[[toData1 objectForKey:@"TotalCount"] intValue ];
			count_2=[[toData2 objectForKey:@"TotalCount"] intValue ];		
			if (count_0>2 && count_1>2 && count_2>2) {
				//限制交易策略的交易數必須大於2
				
				[self optimized_write_to_sql:toData0 dwm:dwm sele012:@"0" tradesystemname:Optimizetradesystem];
				
				//次數第二多策略
				
				[self optimized_write_to_sql:toData1 dwm:dwm sele012:@"1" tradesystemname:Optimizetradesystem];	
				
				//次數第三多策略
				
				[self optimized_write_to_sql:toData2 dwm:dwm sele012:@"2" tradesystemname:Optimizetradesystem];	
				//應垓要刪除最佳化排序的記憶體
				
			}
			else {
				NSLog(@"最佳化過程開始 輸出開始錯誤 可以關閉重新開始最佳化");
				
			}
			//=======================	
			
			
		}
		
		
	}
    
	//記憶體處理
	if ([funct isEqualToString:@"MM3"]) {
		//將自選群組中已經最佳化的商品刪除
		
		//if  (count_0>2 && count_1>2 && count_2>2)	{
        if (YES  ) {
			
		    NSLog(@"將自選群組中已經最佳化的商品刪除=%@ symobl=%@",[prefs objectForKey:@"now_Optimize_group_name" ],symbol);
			NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
			NSString *dir = [paths objectAtIndex:0];
			NSString *filePathw;
			filePathw = [[[NSString alloc] initWithString:[dir stringByAppendingPathComponent:[NSString stringWithFormat: @"WatchList_%@.cplist",[prefs objectForKey:@"now_Optimize_group_name" ]]]] autorelease];
			NSMutableArray *awr;
			awr=[[[NSMutableArray alloc] initWithContentsOfFile:filePathw] autorelease];		
			
			
			int removeindex;
			removeindex=-1;
			if ([awr count]>0) {
				for (int si=0; si<[awr count]; si++) {
					
					NSArray *copm=[[awr objectAtIndex:si] componentsSeparatedByString:@"_"];				
					if ([[copm objectAtIndex:0] isEqualToString:symbol]) {
						removeindex=si;
						
					}
				}
				
				
			}
			
			
			if (removeindex>=0) {
				
				[awr removeObjectAtIndex:removeindex];
				[awr writeToFile:filePathw atomically:YES];
			}			
			
		}
		
		
		//如果此程序是由循環最佳化過程鈕所啓動則資料可以全部刪除掉
		{
			
			[downloadobject release];
			downloadobject=nil;
			
			[financialData release];
			financialData=nil;
			
			[financialData_TradeSystem release];
			financialData_TradeSystem=nil;
			
			[financialData_TradeSystem_Optimize release];
			financialData_TradeSystem_Optimize=nil;
            
			memset(Smooth, 0, sizeof(Smooth));					
			memset(price, 0, sizeof(price));					
			memset(Detrender, 0, sizeof(Detrender));		
			memset(Period, 0, sizeof(Period));					
			memset(Q1, 0, sizeof(Q1));					
			memset(l1, 0, sizeof(l1));
			
			memset(jl, 0, sizeof(jl));					
			memset(jQ, 0, sizeof(jQ));					
			memset(l2, 0, sizeof(l2));		
			memset(Q2, 0, sizeof(Q2));					
			memset(Re, 0, sizeof(Re));					
			memset(lm, 0, sizeof(lm));					
			
			memset(SmoothPeriod, 0, sizeof(SmoothPeriod));					
			memset(Phase, 0, sizeof(Phase));					
			memset(DeltaPhase, 0, sizeof(DeltaPhase));		
			memset(alpha, 0, sizeof(alpha));					
			memset(MAMA, 0, sizeof(MAMA));					
			memset(FAMA, 0, sizeof(FAMA));				
            
			
			
		}
		
		
	}
	
	
	[pool release];
    
	if ([funct isEqualToString:@"MM3"]) {
		[self.delgete afterOptimize];
	}
	
	NSLog(@"Caluate_TradeSystem_end");
}


#pragma mark -
#pragma mark 最佳化結果寫入資料庫內
-(void)optimized_write_to_sql:(NSDictionary *)toData dwm:(NSString *)adwm sele012:(NSString *)sele012 tradesystemname:(NSString *)tradesystem {
	NSAutoreleasePool *pool=[[NSAutoreleasePool alloc] init];	
	
	
	NSLog(@"optimized_write_to_sql_start");
	
	
	//將最佳參數寫入到資料庫中
    
	const char *sql = NULL;	
	NSString *tsql;
	//[tsql autorelease];
	
	
	
	
	if ([tradesystem isEqualToString:@"MESA"]){
		tsql=@"SELECT id,code,FastLim,SlowLim FROM ";
		
	}				
	else if([tradesystem isEqualToString:@"LF"]){
		tsql=@"SELECT id,code,BRangeDay,SRangeDay FROM ";
		
		
		
	}					
	
	tsql=[tsql stringByAppendingString:tradesystem];
	tsql=[tsql stringByAppendingString:@"_"];
	tsql=[tsql stringByAppendingString:sele012];
	tsql=[tsql stringByAppendingString:@"_"];
	tsql=[tsql stringByAppendingString:adwm];
	tsql=[tsql stringByAppendingString:@" where code='"];
	tsql=[tsql stringByAppendingString:symbol];
	tsql=[tsql stringByAppendingString:@"'"];
	sql=[tsql UTF8String];	
	
	//啓動資料庫檔案 輸入檔名與副執行檔名稱與全名
    
	NSString *ver;
	ver=[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
	ver=[ver stringByReplacingOccurrencesOfString:@"." withString:@"_"];
	NSString *filename;
	filename=@"data_";
	filename=[filename stringByAppendingString:ver];
	NSString *filenamexx;
	filenamexx=@"sqlite3";
	NSString *fullfilename;
	fullfilename=[filename stringByAppendingString:@"."];
	fullfilename=[fullfilename stringByAppendingString:filenamexx];
	DBHelper *helper =[DBHelper newInstance:filename andEXT:filenamexx andfullname:fullfilename];		
	sqlite3 *database = [helper openDatabase]; 
	sqlite3_stmt *stm;
	
	if(sqlite3_prepare_v2(database, sql, strlen(sql), &stm, NULL)== SQLITE_OK) {
		BOOL havedata;
		havedata=NO;
		
		
		while(sqlite3_step(stm) ==SQLITE_ROW)
		{
			//int row=sqlite3_column_int(stm, 0);
			//NSString *ii=[[NSString alloc] initWithFormat:@"%d" ,row];
			//sqlite3_column_text
			//sqlite3_column_int
			//sqlite3_column_double
			
			
			char *field1=(char *)sqlite3_column_text(stm, 1);
			NSString *ss1=[[NSString alloc]initWithUTF8String:field1];
			char *field2=(char *)sqlite3_column_text(stm, 2);
			NSString *ss2=[[NSString alloc]initWithUTF8String:field2];				
			char *field3=(char *)sqlite3_column_text(stm, 3);
			NSString *ss3=[[NSString alloc]initWithUTF8String:field3];				
			
            NSLog(@"可以找到資料=%@  %@   %@ ",ss1,ss2,ss3);
			[ss1 release];
            [ss2 release];
            [ss3 release];
            havedata=YES;
		}
		
		NSDate *startDate= [toData objectForKey:@"startdate"];	
		NSDateFormatter* starta = [[NSDateFormatter alloc]init];
		[starta setDateFormat:@"yyyy/MM/dd"];
		NSString *wstart = [starta stringFromDate:startDate];
		[starta release];			
		
		
		NSDate *endDate= [toData objectForKey:@"enddate"];	
		NSDateFormatter* enda = [[NSDateFormatter alloc]init];
		[enda setDateFormat:@"yyyy/MM/dd"];
		NSString *wend = [enda stringFromDate:endDate];
		[enda release];				
		//更新
		if (havedata==YES) {
			NSLog(@"UPDATE");
			//更新資料
			const char *update_sql = NULL;	
			NSString *update_tsql;
			
			if ([tradesystem isEqualToString:@"MESA"]){
                
				
				update_tsql= @"UPDATE ";
				update_tsql=[update_tsql stringByAppendingString:tradesystem];
				update_tsql=[update_tsql stringByAppendingString:@"_"];
				update_tsql=[update_tsql stringByAppendingString:sele012];
				update_tsql=[update_tsql stringByAppendingString:@"_"];
				update_tsql=[update_tsql stringByAppendingString:adwm];
				
				update_tsql=[update_tsql stringByAppendingString:@" SET FastLim ='"] ;
				update_tsql=[update_tsql stringByAppendingString:[NSString stringWithFormat:@"%0.03f", [[toData objectForKey:@"FastLim"] floatValue ]]];
				update_tsql=[update_tsql stringByAppendingString:@"' , SlowLim='"];
				update_tsql=[update_tsql stringByAppendingString:[NSString stringWithFormat:@"%0.03f", [[toData objectForKey:@"SlowLim"] floatValue ]]];
				
				
				update_tsql=[update_tsql stringByAppendingString:@"' , winpercentage='"];
				update_tsql=[update_tsql stringByAppendingString:[NSString stringWithFormat:@"%0.03f", [[toData objectForKey:@"WinPercentage"] floatValue ]]];					
				update_tsql=[update_tsql stringByAppendingString:@"' , yearreturn='"];
				update_tsql=[update_tsql stringByAppendingString:[NSString stringWithFormat:@"%0.03f", [[toData objectForKey:@"YearPercentageRealizeGainLoss"] floatValue ]]];							
				update_tsql=[update_tsql stringByAppendingString:@"' , count='"];
				update_tsql=[update_tsql stringByAppendingString:[NSString stringWithFormat:@"%i", [[toData objectForKey:@"TotalCount"] intValue ]]];							
			    update_tsql=[update_tsql stringByAppendingString:@"' , startdate='"];
				update_tsql=[update_tsql stringByAppendingString:wstart];							
				update_tsql=[update_tsql stringByAppendingString:@"' , enddate='"];
				update_tsql=[update_tsql stringByAppendingString:wend];							
				update_tsql=[update_tsql stringByAppendingString:@"' , id_class='"];
				update_tsql=[update_tsql stringByAppendingString:id_class];	
				update_tsql=[update_tsql stringByAppendingString:@"' WHERE code='"];
				update_tsql=[update_tsql stringByAppendingString:symbol];
				update_tsql=[update_tsql stringByAppendingString:@"'"];
				
				update_sql=[update_tsql UTF8String];					
				
                
			}			
			else if([tradesystem isEqualToString:@"LF"]){
				
				update_tsql= @"UPDATE ";
				update_tsql=[update_tsql stringByAppendingString:tradesystem];
				update_tsql=[update_tsql stringByAppendingString:@"_"];
				update_tsql=[update_tsql stringByAppendingString:sele012];
				update_tsql=[update_tsql stringByAppendingString:@"_"];
				update_tsql=[update_tsql stringByAppendingString:adwm];
				
				update_tsql=[update_tsql stringByAppendingString:@" SET BRangeDay ='"] ;
				update_tsql=[update_tsql stringByAppendingString:[NSString stringWithFormat:@"%i", [[toData objectForKey:@"BRangeDay"] intValue ]]];
				update_tsql=[update_tsql stringByAppendingString:@"' , SRangeDay='"];
				update_tsql=[update_tsql stringByAppendingString:[NSString stringWithFormat:@"%i", [[toData objectForKey:@"SRangeDay"] intValue ]]];
				update_tsql=[update_tsql stringByAppendingString:@"' , Bratio='"];
				update_tsql=[update_tsql stringByAppendingString:[NSString stringWithFormat:@"%0.03f", [[toData objectForKey:@"Bratio"] floatValue ]]];
				update_tsql=[update_tsql stringByAppendingString:@"' , Sratio='"];
				update_tsql=[update_tsql stringByAppendingString:[NSString stringWithFormat:@"%0.03f", [[toData objectForKey:@"Sratio"] floatValue ]]];
                
				
				update_tsql=[update_tsql stringByAppendingString:@"' , winpercentage='"];
				update_tsql=[update_tsql stringByAppendingString:[NSString stringWithFormat:@"%0.03f", [[toData objectForKey:@"WinPercentage"] floatValue ]]];					
				update_tsql=[update_tsql stringByAppendingString:@"' , yearreturn='"];
				update_tsql=[update_tsql stringByAppendingString:[NSString stringWithFormat:@"%0.03f", [[toData objectForKey:@"YearPercentageRealizeGainLoss"] floatValue ]]];							
				update_tsql=[update_tsql stringByAppendingString:@"' , count='"];
				update_tsql=[update_tsql stringByAppendingString:[NSString stringWithFormat:@"%i", [[toData objectForKey:@"TotalCount"] intValue ]]];							
			    update_tsql=[update_tsql stringByAppendingString:@"' , startdate='"];
				update_tsql=[update_tsql stringByAppendingString:wstart];							
				update_tsql=[update_tsql stringByAppendingString:@"' , enddate='"];
				update_tsql=[update_tsql stringByAppendingString:wend];							
				update_tsql=[update_tsql stringByAppendingString:@"' , id_class='"];
				update_tsql=[update_tsql stringByAppendingString:id_class];	
				update_tsql=[update_tsql stringByAppendingString:@"' WHERE code='"];
				update_tsql=[update_tsql stringByAppendingString:symbol];
				update_tsql=[update_tsql stringByAppendingString:@"'"];
				
				update_sql=[update_tsql UTF8String];				
				
				
			}			
            
			 
			
			char *errorMsg;
			sqlite3_exec(database, update_sql, NULL, NULL, &errorMsg);					
		}
	    //新增
		else {
			//NSLog(@"INSERT INTO");
			//插入資料
			const char *insert_sql = NULL;	
			NSString *insert_tsql;
			
			if ([tradesystem isEqualToString:@"MESA"]){
				insert_tsql=@"INSERT INTO ";
				insert_tsql=[insert_tsql stringByAppendingString:tradesystem];
				insert_tsql=[insert_tsql stringByAppendingString:@"_"];
				insert_tsql=[insert_tsql stringByAppendingString:sele012];
				insert_tsql=[insert_tsql stringByAppendingString:@"_"];
				insert_tsql=[insert_tsql stringByAppendingString:adwm];
				insert_tsql=[insert_tsql stringByAppendingString:@" (code,FastLim,SlowLim,winpercentage,yearreturn,count,startdate,enddate,id_class) VALUES ('"];
				insert_tsql=[insert_tsql stringByAppendingString:symbol];
				insert_tsql=[insert_tsql stringByAppendingString:@"', '"];
				insert_tsql=[insert_tsql stringByAppendingString:[NSString stringWithFormat:@"%0.03f", [[toData objectForKey:@"FastLim"] floatValue ]]];
				insert_tsql=[insert_tsql stringByAppendingString:@"', '"];
				insert_tsql=[insert_tsql stringByAppendingString:[NSString stringWithFormat:@"%0.03f", [[toData objectForKey:@"SlowLim"] floatValue ]]];
				insert_tsql=[insert_tsql stringByAppendingString:@"', '"];
				insert_tsql=[insert_tsql stringByAppendingString:[NSString stringWithFormat:@"%0.03f", [[toData objectForKey:@"WinPercentage"] floatValue ]]];
				insert_tsql=[insert_tsql stringByAppendingString:@"', '"];
				insert_tsql=[insert_tsql stringByAppendingString:[NSString stringWithFormat:@"%0.03f", [[toData objectForKey:@"YearPercentageRealizeGainLoss"] floatValue ]]];
				insert_tsql=[insert_tsql stringByAppendingString:@"', '"];
				insert_tsql=[insert_tsql stringByAppendingString:[NSString stringWithFormat:@"%i", [[toData objectForKey:@"TotalCount"] intValue ]]];
				
				insert_tsql=[insert_tsql stringByAppendingString:@"', '"];
				insert_tsql=[insert_tsql stringByAppendingString:wstart];
				insert_tsql=[insert_tsql stringByAppendingString:@"', '"];
				insert_tsql=[insert_tsql stringByAppendingString:wend];
				insert_tsql=[insert_tsql stringByAppendingString:@"', '"];
				insert_tsql=[insert_tsql stringByAppendingString:id_class];
				
				insert_tsql=[insert_tsql stringByAppendingString:@"')"];
				
			}				
			else if([tradesystem isEqualToString:@"LF"]){
				insert_tsql=@"INSERT INTO ";
				insert_tsql=[insert_tsql stringByAppendingString:tradesystem];
				insert_tsql=[insert_tsql stringByAppendingString:@"_"];
				insert_tsql=[insert_tsql stringByAppendingString:sele012];
				insert_tsql=[insert_tsql stringByAppendingString:@"_"];
				insert_tsql=[insert_tsql stringByAppendingString:adwm];
				insert_tsql=[insert_tsql stringByAppendingString:@" (code,BRangeDay,SRangeDay,Bratio,Sratio,winpercentage,yearreturn,count,startdate,enddate,id_class) VALUES ('"];
				insert_tsql=[insert_tsql stringByAppendingString:symbol];
				insert_tsql=[insert_tsql stringByAppendingString:@"', '"];
				insert_tsql=[insert_tsql stringByAppendingString:[NSString stringWithFormat:@"%i", [[toData objectForKey:@"BRangeDay"] intValue ]]];
				insert_tsql=[insert_tsql stringByAppendingString:@"', '"];
				insert_tsql=[insert_tsql stringByAppendingString:[NSString stringWithFormat:@"%i", [[toData objectForKey:@"SRangeDay"] intValue ]]];
				insert_tsql=[insert_tsql stringByAppendingString:@"', '"];
				insert_tsql=[insert_tsql stringByAppendingString:[NSString stringWithFormat:@"%0.03f", [[toData objectForKey:@"Bratio"] floatValue ]]];
				insert_tsql=[insert_tsql stringByAppendingString:@"', '"];
				insert_tsql=[insert_tsql stringByAppendingString:[NSString stringWithFormat:@"%0.03f", [[toData objectForKey:@"Sratio"] floatValue ]]];
				insert_tsql=[insert_tsql stringByAppendingString:@"', '"];
				insert_tsql=[insert_tsql stringByAppendingString:[NSString stringWithFormat:@"%0.03f", [[toData objectForKey:@"WinPercentage"] floatValue ]]];
				insert_tsql=[insert_tsql stringByAppendingString:@"', '"];
				insert_tsql=[insert_tsql stringByAppendingString:[NSString stringWithFormat:@"%0.03f", [[toData objectForKey:@"YearPercentageRealizeGainLoss"] floatValue ]]];
				insert_tsql=[insert_tsql stringByAppendingString:@"', '"];
				insert_tsql=[insert_tsql stringByAppendingString:[NSString stringWithFormat:@"%i", [[toData objectForKey:@"TotalCount"] intValue ]]];
				
				insert_tsql=[insert_tsql stringByAppendingString:@"', '"];
				insert_tsql=[insert_tsql stringByAppendingString:wstart];
				insert_tsql=[insert_tsql stringByAppendingString:@"', '"];
				insert_tsql=[insert_tsql stringByAppendingString:wend];
				insert_tsql=[insert_tsql stringByAppendingString:@"', '"];
				insert_tsql=[insert_tsql stringByAppendingString:id_class];	
				
				insert_tsql=[insert_tsql stringByAppendingString:@"')"];				
				
				
			}					
            
			
			insert_sql=[insert_tsql UTF8String];
			char *errorMsg;
			sqlite3_exec(database, insert_sql, NULL, NULL, &errorMsg);
			
			
		}
		
	}
    //結束查詢作業
	sqlite3_finalize(stm);		
	//[helper closeDatabase];
	//***********************	
    
	
	[pool release];
}


#pragma mark -
#pragma mark 最佳化排序方法

//勝率排序方法
NSInteger comparator_WinPercentage( NSMutableDictionary *d1, NSMutableDictionary *d2, void *context )
{
	return [[d2 objectForKey:@"WinPercentage"] compare:[d1 objectForKey:@"WinPercentage"]];
}
//年報酬慮排序方法
NSInteger comparator_YearPercentageRealizeGainLoss( NSMutableDictionary *d1, NSMutableDictionary *d2, void *context )
{
	return [[d2 objectForKey:@"YearPercentageRealizeGainLoss"] compare:[d1 objectForKey:@"YearPercentageRealizeGainLoss"]];
}
//交易次數排序方法
NSInteger comparator_TotalCount( NSMutableDictionary *d1, NSMutableDictionary *d2, void *context )
{
	return [[d2 objectForKey:@"TotalCount"] compare:[d1 objectForKey:@"TotalCount"]];
}


#pragma mark -
#pragma mark 個別技術指標

-(void)LF_record:(NSMutableDictionary *)csvDict
		 index_i:(int)i 
	  N_Indentfy:(NSString *)identfy
	 P_BRangeDay:(int)BRangeDay
	 P_SRangeDay:(int)SRangeDay
		P_Bratio:(float)Bratio
		P_Sratio:(float)Sratio
	  I_average1:(float)average1
	I_average1_1:(float)average1_1
		 I_close:(float)close 
		  I_high:(float)high
		   I_low:(float)low
	   I_close_1:(float)close_1
	   O_LFCtemp:(LFcaluateTemp *)LFcalcuate{
	
	// NSAutoreleasePool *pool=[[NSAutoreleasePool alloc] init];
	
	 //NSLog(@"LF=%@ 參數BRangeDay=%i SRangeDay=%i Bratio=%0.03f Sratio=%0.03f",identfy,BRangeDay,SRangeDay,Bratio,Sratio);
	
	//買方之區間最高與最低差價
	float BRangeHigh,BRangeLow,BRange;
	{
		if (i>=BRangeDay) {
			BRangeHigh=high;
			for (int k=i;k>(i-BRangeDay) ; k--) {
				NSDictionary *fData = (NSDictionary *)[financialData objectAtIndex:k];		 
				if ([[fData objectForKey:@"high"] floatValue]>=BRangeHigh) {
					BRangeHigh=[[fData objectForKey:@"high"] floatValue];
				};			
			}			
			
		}
		else {
			BRangeHigh=high;
		}

		if (i>=BRangeDay) {
			BRangeLow=low;
			for (int k=i;k>(i-BRangeDay) ; k--) {
				NSDictionary *fData = (NSDictionary *)[financialData objectAtIndex:k];		 
				if ([[fData objectForKey:@"low"] floatValue]<=BRangeLow) {
					BRangeLow=[[fData objectForKey:@"low"] floatValue];
				};			
			}			
			
		}
		else {
			BRangeLow=low;			
		}

		
	}
	BRange=BRangeHigh-BRangeLow; //Brange 表示買方策略區間的最高價與最低價之差
	
	//賣方之區間最高與最低差價
	float SRangeHigh,SRangeLow,SRange;
	{
		
        if (i>=SRangeDay) {
			SRangeHigh=high;
			for (int k=i;k>(i-SRangeDay) ; k--) {
				NSDictionary *fData = (NSDictionary *)[financialData objectAtIndex:k];		 
				if ([[fData objectForKey:@"high"] floatValue]>=SRangeHigh) {
					SRangeHigh=[[fData objectForKey:@"high"] floatValue];
				};			
			}			
			
		}
        else{
             SRangeHigh=high;
        }
        
       
		if (i>=SRangeDay) {
            SRangeLow=low;
			for (int k=i;k>(i-SRangeDay) ; k--) {
				NSDictionary *fData = (NSDictionary *)[financialData objectAtIndex:k];		 
				if ([[fData objectForKey:@"low"] floatValue]<=SRangeLow) {
					SRangeLow=[[fData objectForKey:@"low"] floatValue];
				};			
			}			
			
		}
        else{
         SRangeLow=low;        
        }
        
	}
	SRange=SRangeHigh-SRangeLow; //Srange 表示賣方策略區間的最高價與最低價之差		
	//NSLog(@"srange=%f",SRange);
    
    
	//開始計算笑傲曲線的重要數值
	if (i>=10){
		if (LFcalcuate.LF_b==0 && LFcalcuate.LF_s==0 && close>average1 & close_1<average1_1 ) {
			LFcalcuate.LF_b=1; 
			LFcalcuate.LF_s=0;
			LFcalcuate.LF_bout=close-BRange*Bratio;
			LFcalcuate.LF_sout=0;
		}
		if (LFcalcuate.LF_b==1 & LFcalcuate.LF_bout+BRange<close) {
			LFcalcuate.LF_bout=LFcalcuate.LF_bout+BRange*Bratio;
		}
		if (LFcalcuate.LF_b==1 && close<LFcalcuate.LF_bout) {
			LFcalcuate.LF_b=0;
			LFcalcuate.LF_s=1;
			LFcalcuate.LF_sout=close+SRange*Sratio;
			LFcalcuate.LF_bout=0;
		}
		
		
		if (LFcalcuate.LF_b==0 && LFcalcuate.LF_s==0 && close<average1 & close_1>average1_1 ) {
			LFcalcuate.LF_s=1;
			LFcalcuate.LF_b=0;
			LFcalcuate.LF_sout=close+SRange*Sratio;	
			LFcalcuate.LF_bout=0;
			
		}		
		if (LFcalcuate.LF_s==1 & LFcalcuate.LF_sout-SRange>close) {
			LFcalcuate.LF_sout=LFcalcuate.LF_sout-SRange*Sratio;
		}	
		if (LFcalcuate.LF_s==1 && close>LFcalcuate.LF_sout) {
			LFcalcuate.LF_s=0;
			LFcalcuate.LF_b=1;
			LFcalcuate.LF_bout=close-BRange*Bratio;
			LFcalcuate.LF_sout=0;
		}
		
		
	} 
    
     //NSLog(@"LF_SOUT=%f close=%f average1=%f close_1=%f average1_1=%f srange=%f brange=%f high=%f low=%f ",LFcalcuate.LF_sout,close,average1,close_1,average1_1,SRange,BRange,high,low);
	//紀錄檔
	{
        //NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
                
        
		 NSDecimalNumber *CBrangehigh =  [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%0.2f",BRangeHigh]] ;		 
		 [csvDict setObject:CBrangehigh forKey:@"CBrangehigh"];			
		 NSDecimalNumber *CBrangelow = [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%0.2f",BRangeLow]]  ;		 
		 [csvDict setObject:CBrangelow forKey:@"CBrangelow"];			
		
		 NSDecimalNumber *CSrangehigh =  [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%0.2f",SRangeHigh]]  ;		 
		 [csvDict setObject:CSrangehigh forKey:@"CSrangehigh"];			
		 NSDecimalNumber *CSrangelow = [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%0.2f",SRangeLow]] ;		 
		 [csvDict setObject:CSrangelow forKey:@"CSrangelow"];			
		
        //[pool release];        
		
		[csvDict setObject:[NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%i",LFcalcuate.LF_b]] forKey:[identfy stringByAppendingString:@"_b"]];			
		[csvDict setObject:[NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%i",LFcalcuate.LF_s]] forKey:[identfy stringByAppendingString:@"_s"]];			
		[csvDict setObject:[NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%0.3f",LFcalcuate.LF_bout]] forKey:[identfy stringByAppendingString:@"_bout"]];			
		[csvDict setObject:[NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%0.3f",LFcalcuate.LF_sout]] forKey:[identfy stringByAppendingString:@"_sout"]];			
		[csvDict setObject:[NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%0.2f",close]] forKey:@"close"];	
		
        //[LFcalcuate autorelease];
	}
	
	
	
	
	
	// [pool release];
	

}



-(float)MovingAverage_record:(NSMutableDictionary *)DictRecord 
					 index_i:(int)i 
				  N_Indentfy:(NSString *)identfy
				 P_movingday:(int)movingday 
					 I_close:(float)close {
	
	float sum;
	float average;
	sum=0;
	if (i>=movingday) {
		for (int k=i;k>(i-movingday) ; k--) {
			NSDictionary *fData = (NSDictionary *)[financialData objectAtIndex:k];		 
			sum=sum+ [[fData objectForKey:@"close"] floatValue];
		}
		average=sum/movingday;
	} 
	else {
		//尚未進入計算區間內 就用收盤價取代
		average=close;
	}
 
		 
	[DictRecord setObject:[NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%0.2f",average]] forKey:identfy];	
	
	 return average;

}

-(void)MESA_record:(NSMutableDictionary *)csvDict
		   index_i:(int)i 
		N_Indentfy:(NSString *)identfy 
		 P_FastLim:(float)FastLim 
		 P_SlowLim:(float)SlowLim
			 fhigh:(float)high
			  flow:(float)low{
	if (i>=10) {
		
		//float FastLim,SlowLim;
		//FastLim=0.25;
		//SlowLim=0.01;		
				
		float price,Smooth,Detrender;
		price=(high +low)/2;
		
		//price[i]=(high +low)/2;
		[csvDict setObject:[NSNumber numberWithFloat:price] forKey: [identfy stringByAppendingString:@"price"]];	
		
		float price_1,price_2,price_3;
		price_1=[[(NSDictionary *)[financialData_Calcuate objectAtIndex:i-1] objectForKey:[identfy stringByAppendingString:@"price"]] floatValue];
		price_2=[[(NSDictionary *)[financialData_Calcuate objectAtIndex:i-2] objectForKey:[identfy stringByAppendingString:@"price"]] floatValue];
		price_3=[[(NSDictionary *)[financialData_Calcuate objectAtIndex:i-3] objectForKey:[identfy stringByAppendingString:@"price"]] floatValue];
		
		Smooth =(4 * price + 3 * price_1 + 2 * price_2 + price_3)/10;		
		
		//Smooth[i] =(4 * price[i] + 3 * price[i-1] + 2 * price[i-2] + price[i-3])/10;
		[csvDict setObject:[NSNumber numberWithFloat:Smooth] forKey: [identfy stringByAppendingString:@"Smooth"]];	
		
		float Smooth_2,Smooth_4,Smooth_6;
		float Period_1;
		Smooth_2=[[(NSDictionary *)[financialData_Calcuate objectAtIndex:i-2] objectForKey:[identfy stringByAppendingString:@"Smooth"]] floatValue];
		Smooth_4=[[(NSDictionary *)[financialData_Calcuate objectAtIndex:i-4] objectForKey:[identfy stringByAppendingString:@"Smooth"]] floatValue];
		Smooth_6=[[(NSDictionary *)[financialData_Calcuate objectAtIndex:i-6] objectForKey:[identfy stringByAppendingString:@"Smooth"]] floatValue];
		Period_1=[[(NSDictionary *)[financialData_Calcuate objectAtIndex:i-1] objectForKey:[identfy stringByAppendingString:@"Period"]] floatValue];
		
		Detrender=(0.0962*Smooth+0.5769*Smooth_2-0.5769*Smooth_4-0.0962*Smooth_6)*(0.075*Period_1+0.54);

		//Detrender[i]=(0.0962*Smooth[i]+0.5769*Smooth[i-2]-0.5769*Smooth[i-4]-0.0962*Smooth[i-6])*(0.075*Period[i-1]+0.54);
		[csvDict setObject:[NSNumber numberWithFloat:Detrender] forKey: [identfy stringByAppendingString:@"Detrender"]];	
		
		float Q1;
		float Detrender_2,Detrender_4,Detrender_6;
		Detrender_2=[[(NSDictionary *)[financialData_Calcuate objectAtIndex:i-2] objectForKey:[identfy stringByAppendingString:@"Detrender"]] floatValue];
		Detrender_4=[[(NSDictionary *)[financialData_Calcuate objectAtIndex:i-4] objectForKey:[identfy stringByAppendingString:@"Detrender"]] floatValue];
		Detrender_6=[[(NSDictionary *)[financialData_Calcuate objectAtIndex:i-6] objectForKey:[identfy stringByAppendingString:@"Detrender"]] floatValue];
		
		Q1=(0.0962*Detrender+0.5769*Detrender_2-0.5769*Detrender_4-0.0962*Detrender_6)*(0.075*Period_1+0.54);
		//Q1[i]=(0.0962*Detrender[i]+0.5769*Detrender[i-2]-0.5769*Detrender[i-4]-0.0962*Detrender[i-6])*(0.075*Period[i-1]+0.54);
		[csvDict setObject:[NSNumber numberWithFloat:Q1] forKey: [identfy stringByAppendingString:@"Q1"]];	
		
		float l1;
		float Detrender_3;
		Detrender_3=[[(NSDictionary *)[financialData_Calcuate objectAtIndex:i-3] objectForKey:[identfy stringByAppendingString:@"Detrender"]] floatValue];
		l1=Detrender_3;
		// l1[i]=Detrender[i-3];		
		[csvDict setObject:[NSNumber numberWithFloat:l1] forKey: [identfy stringByAppendingString:@"l1"]];	
		
	 
	 	float jl;
		float l1_2,l1_4,l1_6;
		l1_2=[[(NSDictionary *)[financialData_Calcuate objectAtIndex:i-2] objectForKey:[identfy stringByAppendingString:@"l1"]] floatValue];
		l1_4=[[(NSDictionary *)[financialData_Calcuate objectAtIndex:i-4] objectForKey:[identfy stringByAppendingString:@"l1"]] floatValue];
		l1_6=[[(NSDictionary *)[financialData_Calcuate objectAtIndex:i-6] objectForKey:[identfy stringByAppendingString:@"l1"]] floatValue];
		jl=(0.0962*l1+0.5769*l1_2-0.5769*l1_4-.0962*l1_6)*(0.075*Period_1+0.54);
		//jl[i]=(0.0962*l1[i]+0.5769*l1[i-2]-0.5769*l1[i-4]-.0962*l1[i-6])*(0.075*Period[i-1]+0.54);	
		[csvDict setObject:[NSNumber numberWithFloat:jl] forKey: [identfy stringByAppendingString:@"jl"]];	
		
		float jQ;
		float Q1_2,Q1_4,Q1_6;
		Q1_2=[[(NSDictionary *)[financialData_Calcuate objectAtIndex:i-2] objectForKey:[identfy stringByAppendingString:@"Q1"]] floatValue];
		Q1_4=[[(NSDictionary *)[financialData_Calcuate objectAtIndex:i-4] objectForKey:[identfy stringByAppendingString:@"Q1"]] floatValue];
		Q1_6=[[(NSDictionary *)[financialData_Calcuate objectAtIndex:i-6] objectForKey:[identfy stringByAppendingString:@"Q1"]] floatValue];
		jQ=(0.0962*Q1+.5769*Q1_2-.5769*Q1_4-0.0962*Q1_6)*(0.075*Period_1+0.54) ;
		//jQ[i]=(0.0962*Q1[i]+.5769*Q1[i-2]-.5769*Q1[i-4]-0.0962*Q1[i-6])*(0.075*Period[i-1]+0.54) ;
		[csvDict setObject:[NSNumber numberWithFloat:jQ] forKey: [identfy stringByAppendingString:@"jQ"]];	
		
		float l2;
		l2=l1-jQ;
		//l2[i]=l1[i]-jQ[i];
		[csvDict setObject:[NSNumber numberWithFloat:l2] forKey: [identfy stringByAppendingString:@"l2"]];	
		
		float Q2;
		Q2=Q1+jl;
		//Q2[i]=Q1[i]+jl[i];
		[csvDict setObject:[NSNumber numberWithFloat:Q2] forKey: [identfy stringByAppendingString:@"Q2"]];	
		
		 
		float l2_1;
		l2_1=[[(NSDictionary *)[financialData_Calcuate objectAtIndex:i-1] objectForKey:[identfy stringByAppendingString:@"l2"]] floatValue];
		l2=0.2*l2+0.8*l2_1;
		//l2[i]=0.2*l2[i]+0.8*l2[i-1];
		[csvDict setObject:[NSNumber numberWithFloat:l2] forKey: [identfy stringByAppendingString:@"l2"]];	
		
		
		float Q2_1;
		Q2_1=[[(NSDictionary *)[financialData_Calcuate objectAtIndex:i-1] objectForKey:[identfy stringByAppendingString:@"Q2"]] floatValue];
		Q2=0.2*Q2+0.8*Q2_1;		
		//Q2[i]=0.2*Q2[i]+0.8*Q2[i-1];
		[csvDict setObject:[NSNumber numberWithFloat:Q2] forKey: [identfy stringByAppendingString:@"Q2"]];	
	    float Re;
		Re=l2*l2_1+Q2*Q2_1;
		//Re[i]=l2[i]*l2[i-1]+Q2[i]*Q2[i-1];
		[csvDict setObject:[NSNumber numberWithFloat:Re] forKey: [identfy stringByAppendingString:@"Re"]];		
		
		float lm;
		lm=l2*Q2_1-Q2*l2_1;
		//lm[i]=l2[i]*Q2[i-1]-Q2[i]*l2[i-1];
		[csvDict setObject:[NSNumber numberWithFloat:lm] forKey: [identfy stringByAppendingString:@"lm"]];		
		
		float Re_1;
		Re_1=[[(NSDictionary *)[financialData_Calcuate objectAtIndex:i-1] objectForKey:[identfy stringByAppendingString:@"Re"]] floatValue];
		Re=0.2*Re+0.8*Re_1;
		//Re[i]=0.2*Re[i]+0.8*Re[i-1];
		[csvDict setObject:[NSNumber numberWithFloat:Re] forKey: [identfy stringByAppendingString:@"Re"]];		
		
		float lm_1;
		lm_1=[[(NSDictionary *)[financialData_Calcuate objectAtIndex:i-1] objectForKey:[identfy stringByAppendingString:@"lm"]] floatValue];
		lm=0.2*lm+0.8*lm_1;
		//lm[i]=0.2*lm[i]+0.8*lm[i-1];
		[csvDict setObject:[NSNumber numberWithFloat:lm] forKey: [identfy stringByAppendingString:@"lm"]];		
 
		float Period;
		Period=0;
		if( lm !=0 && Re !=0 )
		{
			Period= 360/(atan((lm/Re))*180/(4*atan(1)));
			
		}		
		
		if( Period>1.5*Period_1)
			Period=1.5*Period_1;
		
		if(Period<0.67*Period_1)
			Period=0.67*Period_1;
		
		if(Period<6)
			Period=6;
		if(Period>50)
			Period=50;
		
		Period=0.2*Period+0.8*Period_1;		
				[csvDict setObject:[NSNumber numberWithFloat:Period] forKey: [identfy stringByAppendingString:@"Period"]];				
		
		float SmoothPeriod,SmoothPeriod_1;
		SmoothPeriod_1=[[(NSDictionary *)[financialData_Calcuate objectAtIndex:i-1] objectForKey:[identfy stringByAppendingString:@"SmoothPeriod"]] floatValue];
		SmoothPeriod=0.33*Period+0.67*SmoothPeriod_1;		
		
		//	SmoothPeriod[i]=0.33*Period[i]+0.67*SmoothPeriod[i-1];
		[csvDict setObject:[NSNumber numberWithFloat:SmoothPeriod] forKey: [identfy stringByAppendingString:@"SmoothPeriod"]];		
 		

 	  
		
	
		float Phase=0;
		if( l1 !=0 )
			Phase=atan(Q1/l1)*180/(4*atan(1));
		[csvDict setObject:[NSNumber numberWithFloat:Phase] forKey: [identfy stringByAppendingString:@"Phase"]];		
		
		float DeltaPhase,Phase_1;
		Phase_1=[[(NSDictionary *)[financialData_Calcuate objectAtIndex:i-1] objectForKey:[identfy stringByAppendingString:@"Phase"]] floatValue];
		
		DeltaPhase=Phase_1-Phase;
		[csvDict setObject:[NSNumber numberWithFloat:DeltaPhase] forKey: [identfy stringByAppendingString:@"DeltaPhase"]];		
		
		if(DeltaPhase<1)
			DeltaPhase=1;
		float alpha;
		
		 		
		
		alpha=FastLim/DeltaPhase;
		
		if(alpha<SlowLim)
			alpha=SlowLim;
		
		if( alpha>FastLim)
			alpha=FastLim;
		
		float MAMA_1,FAMA_1;
		MAMA_1=[[(NSDictionary *)[financialData_Calcuate objectAtIndex:i-1] objectForKey:[identfy stringByAppendingString:@"MAMA"]] floatValue];
		FAMA_1=[[(NSDictionary *)[financialData_Calcuate objectAtIndex:i-1] objectForKey:[identfy stringByAppendingString:@"FAMA"]] floatValue];
		
	    float MAMA,FAMA;
		
		MAMA=alpha*price+(1-alpha)*MAMA_1;
		FAMA=0.5*alpha*MAMA+(1-0.5*alpha)*FAMA_1;		
		
		[csvDict setObject:[NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%0.3f",MAMA]] forKey: [identfy stringByAppendingString:@"MAMA"]];		
		[csvDict setObject:[NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%0.3f",FAMA]] forKey: [identfy stringByAppendingString:@"FAMA"]];		
		
		/*
		
		MAMA[i]=alpha[i]*price[i]+(1-alpha[i])*MAMA[i-1];
		FAMA[i]=0.5*alpha[i]*MAMA[i]+(1-0.5*alpha[i])*FAMA[i-1];			
		
		NSDecimalNumber *CMAMA = [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%0.3f",MAMA[i]]];		 
		[csvDict setObject:CMAMA forKey:@"Cmesa1_mama"];	
		NSDecimalNumber *CFAMA = [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%0.3f",FAMA[i]]];		 
		[csvDict setObject:CFAMA forKey:@"Cmesa1_fama"];		
		
		*/ 
		
		
	}	
	else {
		[csvDict setObject:[NSNumber numberWithFloat:(high +low)/2] forKey: [identfy stringByAppendingString:@"price"]];	
		
		[csvDict setObject:[NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%0.3f",0.0]] forKey: [identfy stringByAppendingString:@"MAMA"]];
		[csvDict setObject:[NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%0.3f",0.0]] forKey: [identfy stringByAppendingString:@"FAMA"]];
	}
							 
							
}


#pragma mark -
#pragma mark 清除記憶體 方法

-(void)dealloc_financialData{
	NSLog(@"*****************dealloc_financialData=%@",symbol);
    // NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    //標記: 清除最小股票單位資料物件 (執行釋放記憶體 緒)
        [downloadobject  release];
         downloadobject=nil;
    
        [financialData  release];
        financialData=nil; 
    
        [financialData_Calcuate release];
         financialData_Calcuate=nil;  
    
        [aParaObject release];
        aParaObject=nil;    
    
        [financialData_TradeSystem  release];
        financialData_TradeSystem=nil; 
     // [self dealloc];
   // [pool release];
 

}
#pragma mark -
#pragma mark 離開處理 方法

-(void)dealloc{
	NSLog(@"*****************Dataobject dealoc=%@",symbol);
	 
	
	//網路資料下載物件
	[downloadobject release];
    //[code release];	
	[symbol release];
     symbol=nil;
	[name release];
	 
    [tradedate release];
    [tradetime release];
    [updown release];
    [updownPercent release];
    [Nupdwon release];
    [Nupdwonpercent release];
    [s_open release];
    [s_high release];
    [s_low release];
    [activity release];
    [his release];
    [id_class release];
	//時間序列資料
	[financialData release];
	 
	[financialData_Calcuate release];
	 
	
	//時間序列資料的屬性特徵
    
    [overallHigh release];
    [overallLow release];
    [VoloverallHigh release];
    [VoloverallLow release];
	 
    //即時資料
	[rHigh release];//最高價
	 
	 
	//[financialData release];
    [symbol_xxtradexx release];
	
   // [financialData_Calcuate release];
	//financialData_Calcuate=nil;
	
	 [aParaObject release];
	 aParaObject=nil;
	 
	[super dealloc];	
	
}

-(int)Date_weekday:(NSDate *)thedate{
	NSUInteger flags = NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSWeekdayCalendarUnit ;
	
	
	NSCalendar *calendar = [NSCalendar currentCalendar];
	
	
	NSDateComponents *dComponents = [calendar components:flags fromDate:thedate];
	int dayNum = [dComponents weekday];
	
	return dayNum;	
	
	
	
}
  
-(int)Date_month:(NSDate *)thedate{
	NSUInteger flags = NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSWeekdayCalendarUnit ;
	
	
	NSCalendar *calendar = [NSCalendar currentCalendar];
	
	
	NSDateComponents *dComponents = [calendar components:flags fromDate:thedate];
	int dayNum = [dComponents month];
	
	return dayNum;	  
	
	
	
}

-(int)Date_year:(NSDate *)thedate{
	NSUInteger flags = NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSWeekdayCalendarUnit ;
	
	
	NSCalendar *calendar = [NSCalendar currentCalendar];
	
	
	NSDateComponents *dComponents = [calendar components:flags fromDate:thedate];
	int dayNum = [dComponents year];
	
	return dayNum;	  
	
	
	
}

@end
